I have used Pygame with python 2.7 before but recently I ‘upgraded’ to python 3.2. I downloaded and installed the newest version of Pygame which is said to work with this version of python. I have, however, had this rather frustrating error on what should be a simple block of code. The code is:
import pygame, random
title = "Hello!"
width = 640
height = 400
pygame.init()
screen = pygame.display.set_mode((width, height))
running = True
clock = pygame.time.Clock()
pygame.display.set_caption(title)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.quit():
running = False
else:
print(event.type)
clock.tick(240)
pygame.quit()
And every single time I run it I get:
17
1
4
Traceback (most recent call last):
File "C:/Users/David/Desktop/hjdfhksdf.py", line 15, in <module>
for event in pygame.event.get():
pygame.error: video system not initialized
Why am I getting this error?
asked Jul 30, 2011 at 6:12
0
if event.type == pygame.quit():
In the line above, you’re calling pygame.quit()
which is a function, while what you really want is the constant pygame.QUIT
. By calling pygame.quit()
, pygame is no longer initialized, which is why you get that error.
Thus, changing the line to:
if event.type == pygame.QUIT: # Note the capitalization
Will solve your problem.
It’s important to note that pygame.quit()
will not exit the program.
vallentin
22.7k6 gold badges57 silver badges79 bronze badges
answered Jul 30, 2011 at 21:10
MerigrimMerigrim
84610 silver badges18 bronze badges
0
Hi there: I got the following error.
I run the following code posted below in Pycharm ( iOS Catalina) (Python 3.8) and I got an error :
for event in pygame.event.get():
pygame.error: video system not initialized_
import sys
import pygame
def run_game():
pygame.init()
screen = pygame.display.set_mode((1200,800))
pygame.display.set_caption(«Alien Invasion»)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.display.flip()
run_game()
Thanks in advance if someone helps me to solve this issue.
The given code is running the while True
loop before initializing pygame.
import sys import pygame def run_game(): pygame.init() screen = pygame.display.set_mode((1200,800)) pygame.display.set_caption("Alien Invasion") while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() pygame.display.flip() run_game()
One way to fix this is to move the while loop into the run_game
function.
import sys import pygame def run_game(): pygame.init() screen = pygame.display.set_mode((1200,800)) pygame.display.set_caption("Alien Invasion") while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() pygame.display.flip() run_game()
Great! Your advice has worked. Now, I got a beautiful black screen. You’ve
made my day.
…
On Tue, Jan 21, 2020 at 11:31 AM Charles ***@***.***> wrote:
The given code is running the while True loop before initializing pygame.
import sysimport pygamedef run_game():
pygame.init()
screen = pygame.display.set_mode((1200,800))
pygame.display.set_caption(«Alien Invasion»)while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.display.flip()
run_game()
One way to fix this is to move the while loop into the run_game function.
import sysimport pygame
def run_game():
pygame.init()
screen = pygame.display.set_mode((1200,800))
pygame.display.set_caption(«Alien Invasion»)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.display.flip()
run_game()
—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
<#1557?email_source=notifications&email_token=AHHXE6ECOEUVPYBHM2RINELQ64POFA5CNFSM4KGIE3JKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEJQLWNY#issuecomment-576764727>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AHHXE6BZBAHUUGC5JAFUQ7TQ64POFANCNFSM4KGIE3JA>
.
#python #pygame
Вопрос:
Я получаю эту ошибку всякий раз, когда пытаюсь выполнить свой pygame
код: pygame.error: video system not initialized
from sys import exit
import pygame
from pygame.locals import *
black = 0, 0, 0
white = 255, 255, 255
red = 255, 0, 0
green = 0, 255, 0
blue = 0, 0, 255
screen = screen_width, screen_height = 600, 400
clock = pygame.time.Clock()
pygame.display.set_caption("Physics")
def game_loop():
fps_cap = 120
running = True
while running:
clock.tick(fps_cap)
for event in pygame.event.get(): # error is here
if event.type == pygame.QUIT:
running = False
screen.fill(white)
pygame.display.flip()
pygame.quit()
exit()
game_loop()
#!/usr/bin/env python
Ответ №1:
Ты никуда не звонил pygame.init()
.
См. Основное руководство по вводной части или специальное руководство по импорту и инициализации, в котором объясняется:
Прежде чем вы сможете многое сделать с pygame, вам нужно будет его инициализировать. Самый распространенный способ сделать это-просто сделать один звонок.
pygame.init()
Это будет попытка инициализировать все модули pygame для вас. Не все модули pygame необходимо инициализировать, но это автоматически инициализирует те, которые это делают. Вы также можете легко инициализировать каждый модуль pygame вручную. Например, чтобы только инициализировать модуль шрифта, вы просто вызовете.
В вашем конкретном случае, вероятно pygame.display
, это жалоба на то, что вы позвонили либо its set_caption
, либо its flip
, не позвонив init
сначала. Но на самом деле, как говорится в руководстве, лучше просто init
все наверху, чем пытаться выяснить, что именно нужно инициализировать, когда.
Ответ №2:
Изменение кода на этот позволяет избежать этой ошибки. во время работы: clock.tick(fps_cap)
for event in pygame.event.get(): #error is here
if event.type == pygame.QUIT:
running = False
pygame.quit()
if running:
screen.fill(white)
pygame.display.flip()
Ответ №3:
Вы получаете ошибку, потому что пытаетесь установить заголовок окна (с set_caption()
), но вы не создали окно pygame, поэтому ваша screen
переменная-это просто кортеж, содержащий размер вашего будущего окна.
Чтобы создать окно pygame, вам нужно позвонить pygame.display.set_mode(windowSize)
.
Удачи 🙂
Ответ №4:
Недавно у меня возникла эта проблема, и я обнаружил странную и необычную ошибку в написанном мной коде-только после того, как прочитал его и перечитал дюжину раз в течение 10 минут, пытаясь запустить файл (который выглядел идеально) дюжину раз.
Там был pygame.init()
. Там была screen = pygame.display.set_mode((size))
переменная размера, доступная в глобальном пространстве имен.
Оказывается, это был основной игровой цикл.
# main game loop
while RUNNING == True:
for tneve in pygame.event.get():
if tneve.type == QUIT:
print(tneve)
RUNNING = False
loop()
render()
CLOCK.tick(FPS)
cleanup()
# End
Какая боль!
P.S. Проблема заключается в слишком большом отступе всего, что приведено ниже RUNNING = False
.
Комментарии:
1. Это отличная история, Тим, и спасибо, что поделился с нами, но она не отвечает на вопрос и описывает другую проблему.
Ответ №5:
- Если вы это сделаете
pygame.init()
, то решите проблему с инициализацией видеосистемы. но вы получаете следующую ошибку, например:
(
AttributeError: tuple object has no attribute 'fill'
) это.
- эта проблема решается, когда вы делаете это
screen = pygame.display.set_mode((600, 400))
но не делать так, как
screen = screen_width, screen_height = 600, 400
- Тогда вся проблема будет решена.
Ответ №6:
Я внес некоторые изменения в ваш код:
import os
import sys
import math
import pygame
import pygame.mixer
from pygame.locals import *
pygame.init()
black = 0, 0, 0
white = 255, 255, 255
red = 255, 0, 0
green = 0, 255, 0
blue = 0, 0, 255
screen = pygame.display.set_mode((600, 400))
clock = pygame.time.Clock()
pygame.display.set_caption("Physics")
while True:
clock.tick(120)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
screen.fill(green)
pygame.display.flip()
Ответ №7:
Вам просто нужно добавить
exit()
Чтобы остановить выполнение
примера кода :
for event in pygame.event.get(): #error is here
if event.type == pygame.QUIT:
running = False
exit() # Solution
Ответ №8:
Вы должны добавить:
pygame.init()
Прежде чем выйти из дисплея, вы должны остановить цикл while.
Ответ №9:
Если вы используете class
для своего pygame
окна, не используйте pygame.init()
в своем class
. Используйте pygame.init()
в нижеприведенных библиотеках.
Ответ №10:
- Вам необходимо инициализировать pygame с помощью этой команды
pygame.init
If the problem is not solved then following this step
- эта проблема возникает при использовании бета-версии.
- поэтому я предлагаю, пожалуйста, использовать новую, старую версию(если сейчас есть python 3.8, вам нужно установить python 3.7).
- Теперь перейдите к терминалу python и установите pygame (pip install pygame)
- теперь проблема решена…
Уведомления
- Начало
- » Python для новичков
- » video system not initialized
#1 Апрель 13, 2016 16:17:47
video system not initialized
import pygame
WHITE = (255, 255, 255)
pygame.init()
(6,0) <– выдает, что это означает интересно знать бы -)
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption(“My Game”)
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(WHITE)
pygame.display.flip()
clock.tick(60)
pygame.quit()
Здравствуйте! Пытаюсь освоить Питон. (знаний программирования вобще нет) После нажатия ‘Enter’, открывшееся окно успевает поменять фон на белый, и закрывается с ошибкой: video system not initialized (видеосистема не инициализируется). Что это может означать, проблема с дравами на видеокарту?
Офлайн
- Пожаловаться
#2 Апрель 13, 2016 16:23:26
video system not initialized
Pygame нет, но попробуй вот так код поправить :
import pygame WHITE = (255, 255, 255) pygame.init() size = (700, 500) screen = pygame.display.set_mode(size) pygame.display.set_caption('My Game') screen.fill(WHITE) pygame.display.flip() clock = pygame.time.Clock() clock.tick(60) done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pygame.quit()
Хотя вроде вспомнил, что я сейчас полную чушь сказал. Это скорее всего не поможет.
Отредактировано Lestoroer (Апрель 13, 2016 16:30:15)
Офлайн
- Пожаловаться
#3 Апрель 13, 2016 16:26:20
video system not initialized
Traceback (most recent call last):
File “<pyshell#23>”, line 2, in <module>
for event in pygame.event.get():
pygame.error: video system not initialized
не знаю как отступы сделать.. Полная ошибка выглядит так..
Отредактировано kapaky (Апрель 13, 2016 16:27:20)
Офлайн
- Пожаловаться
#4 Апрель 13, 2016 16:30:43
video system not initialized
kapaky
Traceback (most recent call last): File “<pyshell#23>”, line 2, in <module> for event in pygame.event.get():pygame.error: video system not initializedне знаю как отступы сделать.. Полная ошибка выглядит так..
Снова попробуй скопировать, я отредактировал
Офлайн
- Пожаловаться
#5 Апрель 13, 2016 16:43:41
video system not initialized
pygame.display.set_caption(‘My Game’)
screen.fill(WHITE)
если вобще убрать эти строчки, та же ошибка
Офлайн
- Пожаловаться
#6 Апрель 13, 2016 17:55:11
video system not initialized
все перепробовал, даже от имени администратора запускал. Та же ошибка.
мне кажется что, когда я скачивал “pygame” он был не полный. Если такое бывает.?
Офлайн
- Пожаловаться
#7 Апрель 16, 2016 10:26:50
video system not initialized
может после, когда сам во всем разберусь, то объясню, почему именно так. Но пока работает следующая схема.
>>> import pygame,sys
>>> pygame.init()
>>> from pygame.locals import * <—- Эта штука важна (1)
>>> size= (400,600) <—- Скобки квадратные только
>>> dis=pygame.display.set_mode(size)
>>> while True:
for event in pygame.event.get():
if event.type == QUIT: <—– (1) влияет на выход. Без нее выдает, что переменной ‘QUIT’ нет
pygame.quit()
sys.exit()
pygame.display.update()
Теперь все работает, закрывается, когда пользователь нажмет закрыть (через крестик как обычно)
Отредактировано kapaky (Апрель 16, 2016 10:28:52)
Офлайн
- Пожаловаться
#8 Апрель 6, 2017 18:01:27
video system not initialized
kapaky
Форум сайта python.su
Получилось разобраться?
Офлайн
- Пожаловаться
- Начало
- » Python для новичков
- » video system not initialized
The pygame.error: video system not initialized error is prominent in game development and has its base of reasons. This article explores the environment around those reasons by discussing how they cause the error.
We will also look at how those reasons can be fixed to ensure a smooth game development experience. This article has the potential to clear your concepts about the occurrence of this error.
Pygame.error: video system not initialized is a common error that originates in game development using Python. The reasons are pygame.init() function not being called, not stopping the main loop upon the closure of the game. The absence of indentation and lack of attachment of display are secondary reasons.
– The Pygame.init() Function Not Called
This reason is most likely to cause the pygame error as the pygame.init() function has an important purpose. A pygame has to be initialized first before any functionality is performed on it. And the pygame.init() function is called to initialize every relevant pygame module for the user. This function not being called means that the pygame modules are not properly initialized.
Keep in mind that not all pygame modules have to undergo initialization. However, this function automatically initializes all those that have to be initialized. Since the pygame.init() function is not called the pygame.display module complains about the calling of its flip or set_caption without the initial calling of its init. This corresponds to the pygame.error: display surface quit error.
– Main Loop Not Stopped
The pygame video system not initialized mouse error can also occur if the main loop of the implementation is not stopped upon exiting the game. This is accompanied by certain indentation issues that also contribute to the error. The main loop involves the pygame.quit() function that is called inside game(). Due to this function, pygame is uninitialized, which further leads to the failure of all attempts that can call its functionality.
– Lack of Attachment of Display
Lack of proper indentation contributes to a lack of attachment of display that causes the pygame.error video system not initialized Raspberry Pi. The basic principle of this reason varies with the version of pi used as well as OS inc lite or desktop. In most cases, the usage of a desktop version of OS and pi4 results in the absence of a display attached. As a result, the frame or desktop buffer is not set up properly, which, in turn, leads to the error.
How to Solve Video System Not Initialized Issue
Pygame.error video system not initialized can be fixed by stopping the main loop of implementation with the exit() function. The pygame.init() error is caused by its function not being called and can be solved with the import and initialization of pygame modules. Finally, the usage of raspi-config can fix the error.
– Import of Pygame Modules
The package of pygame modules has to be initially imported to solve the error. The import has become much easier for the users since pygame has updated to its 1.4 version. For most of the games, pygame can be completely imported so that the pygame.init() function is called to solve the error. The following is a snippet that shows how pygame can be imported:
import pygame
from pygame.locals import *
Explaining the snippet: The first line of the snippet is the most important one as it manages the import of every relevant module of pygame into its package. Apart from this, the involvement of the second line is optional in the snippet. Its usage places a limited set of functions and constants within the global namespace of the implementation.
Example of a font module: It is important to note here that the inclusion of a large number of pygame modules is optional. As an example, the font module can be imported initially to be initialized. With “import pygame” as the first line, the font module is checked by pygame to see if it is available.
It is imported as “pygame.font” if it is available. On the flip side, “pygame.font” is set to none, which makes testing easier later to check the availability of the font module.
– Initialization of Pygame Modules
All of the pygame modules can be easily initialized by hand, for example, the initialization of the font module by calling the pygame.init() function. The usage of this function is considered to be better than considering the content that has to be initialized and its time.
The initialization and import of a pygame is a simple and flexible process that enables control, for the user, over the whole implementation. As a collection of various modules, pygame acts as an individual Python package where some of its modules are written in Python and others are written in C.
As for the example above, the font module can be initialized just by calling pygame.font.init(). This shows that the initialization of any module also includes the get.init() function, which returns as TRUE in the case of a successful initialization of the module. The init() function can be called multiple times for any given module.
There is a quit() function as well that cleans up the initialized modules; however its explicit calling is optional as all initialized modules are cleanly quit by pygame.
– Stopping the Main Loop
The main loop has to be stopped while exiting the game to solve the error. For this, the pygame.quit() function should be called whenever a Python session has to be terminated. This should be followed by the calling of the exit() function. It can be done by setting the ‘finish value’ as TRUE and the ‘start value’ as FALSE if game() is called multiple times in an interactive game session.
– Changing Screen Resolution in Pixel
The usage of code tags is important in the implementation to fix the lack of attachment for pygame without display. For this, a default resolution has to be set with the involvement of raspi-config.
The screen resolution can be changed in Pixel (Raspbian) by clicking on the menu of Raspberry Pi present on the taskbar. There may be a difference in the exact names of items in the menu that correspond to various versions of Raspbian.
The Pathway Followed To Change Screen Resolution
The pathway is initiated by the Preferences section, which is followed by Screen Configuration to arrive at the Screen Layout Editor option. The following route involves Configure, Screens, Virtual1, and Resolution in succession. After that, the selection of the required resolution is made, and the next green check button is clicked. The final step of the pathway is an ‘OK’ popup that has to be clicked by the user.
Conclusion
This article dissected the error that occurs during game development in Python. Now you have enough knowledge to eliminate the error yourself. To be sure, the following are the main points of its reasons and their fixes:
- The error occurs due to the pygame.init() function not being called as it initializes every relevant pygame module for the user.
- The main loop of the implementation has to be stopped to prevent the occurrence of the error.
- The error can also occur in Raspberry Pi due to a lack of attachment of display with a frame or desktop buffer not set up properly.
- The package of pygame modules has to be imported and initialized so that the pygame.init() can be called.
- The screen resolution can be changed by setting up a default resolution with the involvement of raspi-config.
You can enable this article to facilitate you in providing intricate details about the error by coming back to it.
- Author
- Recent Posts
Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.
-
panayiotis
- Posts: 10
- Joined: Fri Dec 21, 2018 11:35 am
pygame.error: video system not initialised
Hi all,
I am trying to build a robot and using pygame to control it. I have built in a camera and tested it works fine, but when I integrate the code to record a video using pygame I get the above error. I have included the code and the full error below.
Can you pls help?
Many thanks!
Code: Select all
import pygame
import RPi.GPIO as GPIO
import time
#import picamera and datetime (to use in unique file naming)
from picamera import PiCamera
from datetime import datetime
#Open a Pygame window to allow it to detect user events
screen = pygame.display.set_mode([240, 160])
#setup camera
camera = PiCamera()
camera.resolution = (1280,720)
camera.framerate = (25)
record = 0 #set up a variable to be set to 1 when recording
#set GPIO numbering mode and define output pins
GPIO.setmode(GPIO.BOARD)
GPIO.setup(29,GPIO.OUT)
#flashes LEDs when all running, and also lets camera settle
for x in range(1, 5):
GPIO.output(29,True)
time.sleep(0.5)
GPIO.output(29,False)
time.sleep(0.5)
try:
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
elif event.key == pygame.K_r:
if record == 0:
record = 1
moment = datetime.now()
GPIO.output(29,True)
camera.start_recording('/home/pi/Videos/vid_%02d_%02d_%02d.mjpg' % (moment.hour, moment.minute, moment.second))
elif event.key == pygame.K_t:
if record == 1:
record = 0
GPIO.output(29,False)
camera.stop_recording()
finally:
#GPIO cleanup
GPIO.cleanup()
Error below:
File «/home/pi/Robots/Robot_Camera.py», line 33 in <module> for event in pygame.event.get():
pygame.error: video system not initialized
Last edited by panayiotis on Thu Nov 04, 2021 1:45 pm, edited 1 time in total.
-
pcmanbob
- Posts: 13356
- Joined: Fri May 31, 2013 9:28 pm
- Location: Mansfield UK
Re: pygame.error: video system not initialised
Thu Nov 04, 2021 11:44 am
So first off you code has no indentation so it wont work , when posting code you need to use code tags..viewtopic.php?t=84477
Secondly you need to tell us which pi you are using and exactly which OS inc lite or desktop.
I suspect you are using a desktop version of the OS on a pi4 with no display attached so there is not desktop/frame buffer set up.
If this is the problem you will need to set a default resolution using raspi-config.
https://www.raspberrypi.com/documentati … ation.html
We want information… information… information……………………no information no help
The use of crystal balls & mind reading are not supported
-
panayiotis
- Posts: 10
- Joined: Fri Dec 21, 2018 11:35 am
Re: pygame.error: video system not initialised
Thu Nov 04, 2021 12:40 pm
Thank you for this and apologies for the lack of indentation — when i pasted the code it had the correct indentation, but it somehow got lost when I posted — I have to admit I am quite new to this, so I must have handled sth incorrectly.
I am using a Pi 3B on the default Pi Desktop OS. I am using DMT mode 58 for resolution. Also, worth noting, the camera records correctly when I use a code to simply make a 5sec recording, but fails when I try to integrate to pygame.
Hope this extra info helps paint a more accurate picture. Tahnks again for your help!
-
DirkS
- Posts: 10809
- Joined: Tue Jun 19, 2012 9:46 pm
- Location: Essex, UK
Re: pygame.error: video system not initialised
Thu Nov 04, 2021 1:02 pm
panayiotis wrote: ↑
Thu Nov 04, 2021 12:40 pm
Thank you for this and apologies for the lack of indentation — when i pasted the code it had the correct indentation, but it somehow got lost when I posted — I have to admit I am quite new to this, so I must have handled sth incorrectly.
Formatting is still there but is only visible in code blocks.
Pls add formatting: edit your post, select all the Python code and then click on the ‘Code’ button.
Then save your post. Code should now be properly formatted.
-
pcmanbob
- Posts: 13356
- Joined: Fri May 31, 2013 9:28 pm
- Location: Mansfield UK
Re: pygame.error: video system not initialised
Thu Nov 04, 2021 5:35 pm
If you are using a Pi 3B then it will not be affected by the lack of a desktop /frame buffer if there is no display connected so your problem is with how you are initializing pygame.
I suggest you read the pygame docs to see how to do it…. https://www.pygame.org/docs/
We want information… information… information……………………no information no help
The use of crystal balls & mind reading are not supported
-
panayiotis
- Posts: 10
- Joined: Fri Dec 21, 2018 11:35 am
Re: pygame.error: video system not initialised
Fri Nov 05, 2021 9:14 am
gordon77 wrote: ↑
Thu Nov 04, 2021 5:57 pm
You need pygame.init()Code: Select all
#Open a Pygame window to allow it to detect user events pygame.init() screen = pygame.display.set_mode([240, 160])
Thank you — I tried that but unfortunately I still get the exact same error message.
-
rpiMike
- Posts: 2265
- Joined: Fri Aug 10, 2012 12:38 pm
- Location: Cumbria, UK
Re: pygame.error: video system not initialised
Fri Nov 05, 2021 10:34 am
What does the following output?
Code: Select all
import pygame
pygame.init()
print(pygame.display.Info())
I get:
pygame 1.9.4.post1
Hello from the pygame community. https://www.pygame.org/contribute.html
<VideoInfo(hw = 0, wm = 1,video_mem = 0
blit_hw = 0, blit_hw_CC = 0, blit_hw_A = 0,
blit_sw = 0, blit_sw_CC = 0, blit_sw_A = 0,
bitsize = 32, bytesize = 4,
masks = (16711680, 65280, 255, 0),
shifts = (16, 8, 0, 0),
losses = (0, 0, 0, 8),
current_w = 1920, current_h = 1080
>
-
panayiotis
- Posts: 10
- Joined: Fri Dec 21, 2018 11:35 am
Re: pygame.error: video system not initialised
Fri Nov 05, 2021 12:41 pm
rpiMike wrote: ↑
Fri Nov 05, 2021 10:34 am
What does the following output?Code: Select all
import pygame pygame.init() print(pygame.display.Info())
I get:
pygame 1.9.4.post1
Hello from the pygame community. https://www.pygame.org/contribute.html
<VideoInfo(hw = 0, wm = 1,video_mem = 0
blit_hw = 0, blit_hw_CC = 0, blit_hw_A = 0,
blit_sw = 0, blit_sw_CC = 0, blit_sw_A = 0,
bitsize = 32, bytesize = 4,
masks = (16711680, 65280, 255, 0),
shifts = (16, 8, 0, 0),
losses = (0, 0, 0, 8),
current_w = 1920, current_h = 1080
>
I see the same apart from the last line, where current_w=1680 and current_h=1050, but I guess this is because I have set DMT Mode 58
-
panayiotis
- Posts: 10
- Joined: Fri Dec 21, 2018 11:35 am
Re: pygame.error: video system not initialised
Fri Nov 05, 2021 1:26 pm
rpiMike wrote: ↑
Fri Nov 05, 2021 12:51 pm
Your code works for me. Do you see the pygame window appear?
Yes — I can see it appear. Also every other function works fine (I have stripped the code of the commands for moving the robot around, but they work fine) — it is only the camera commands that appear to have issues for me. I would consider a hardware issue, but the camera works fine on its own…
-
rpiMike
- Posts: 2265
- Joined: Fri Aug 10, 2012 12:38 pm
- Location: Cumbria, UK
Re: pygame.error: video system not initialised
Fri Nov 05, 2021 3:50 pm
panayiotis wrote: ↑
Fri Nov 05, 2021 1:26 pm
it is only the camera commands that appear to have issues for me.
So has your original error «in <module> for event in pygame.event.get():
pygame.error: video system not initialized» now gone?
What are the camera command issues?
-
panayiotis
- Posts: 10
- Joined: Fri Dec 21, 2018 11:35 am
Re: pygame.error: video system not initialised
Fri Nov 05, 2021 4:39 pm
rpiMike wrote: ↑
Fri Nov 05, 2021 3:50 pm
panayiotis wrote: ↑
Fri Nov 05, 2021 1:26 pm
it is only the camera commands that appear to have issues for me.So has your original error «in <module> for event in pygame.event.get():
pygame.error: video system not initialized» now gone?What are the camera command issues?
Nope — the error is still there. What I meant before is that I only get the error when I try to record video — moving the robot around works fine, apologies if I was being confusing. What I should also mention is that «mjpg» files only produce a static image for me, so I was using «h264» instead to record video, but I get the error with both file extensions.
-
panayiotis
- Posts: 10
- Joined: Fri Dec 21, 2018 11:35 am
Re: pygame.error: video system not initialised
Sun Nov 07, 2021 11:08 pm
Hi all,
I managed to resolve the issue by moving the pygame.quit() command at the end of the code, introducing a control variable for the loop and use sys.exit.
I have included the code below.
Thanks all for your help and time.
Panayiotis
Code: Select all
import pygame, sys
import RPi.GPIO as GPIO
import time
#import picamera and datetime (to use in unique file naming)
from picamera import PiCamera
from datetime import datetime
pygame.init()
#Open a Pygame window to allow it to detect user events
screen = pygame.display.set_mode([240, 160])
#setup camera
camera = PiCamera()
camera.resolution = (1280,720)
camera.framerate = (25)
record = 0 #set up a variable to be set to 1 when recording
#set GPIO numbering mode and define output pins
GPIO.setmode(GPIO.BOARD)
GPIO.setup(29,GPIO.OUT)
#flashes LEDs when all running, and also lets camera settle
for x in range(1, 5):
GPIO.output(29,True)
time.sleep(0.5)
GPIO.output(29,False)
time.sleep(0.5)
keepLooping = True
try:
while keepLooping:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
#pygame.quit()
keepLooping = False
elif event.key == pygame.K_r:
if record == 0:
record = 1
moment = datetime.now()
GPIO.output(29,True)
camera.start_recording('/home/pi/Videos/vid_%02d_%02d_%02d.h264' % (moment.hour, moment.minute, moment.second))
elif event.key == pygame.K_t:
if record == 1:
record = 0
GPIO.output(29,False)
camera.stop_recording()
finally:
#GPIO cleanup
GPIO.cleanup()
pygame.quit()
sys.exit
Return to “Python”