Pygame error video system not initialized как исправить

The “pygame.error: video system not initialized” error can disrupt your game development experience. Click here to understand its reasons and solutions.

Why is pygame error video system not initialized happeningThe 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:How to solve pygame error video system not initialized error

  • 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

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

@javiergoldaraz

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.

@charlesej

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()

@javiergoldaraz

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:

  1. Если вы это сделаете pygame.init() , то решите проблему с инициализацией видеосистемы. но вы получаете следующую ошибку, например:

( AttributeError: tuple object has no attribute 'fill' ) это.


  1. эта проблема решается, когда вы делаете это
 screen = pygame.display.set_mode((600, 400))
 

но не делать так, как

 screen = screen_width, screen_height = 600, 400
 

  1. Тогда вся проблема будет решена.

Ответ №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:

  1. Вам необходимо инициализировать pygame с помощью этой команды pygame.init
     If the problem is not solved then following this step
     
  2. эта проблема возникает при использовании бета-версии.
  3. поэтому я предлагаю, пожалуйста, использовать новую, старую версию(если сейчас есть python 3.8, вам нужно установить python 3.7).
  4. Теперь перейдите к терминалу python и установите pygame (pip install pygame)
  5. теперь проблема решена…

In this post, you will learn about Pygame such as how to fix Pygame. error: video system not initialized so let’s go and start.

Running your pygame code will result in the following error: pygame.error: video system not initialized. It is necessary to initialize Pygame before you can do much with it. This is usually done by calling one method.

Pygame allows you to make pretty much the simplest of codes. The program creates a window and allows you to close it. Unfortunately, I am getting the error pygame.error: video system not initialized.

Contents

  • 1 Fix Pygame. error: video system not initialized
  • 2 pygame.error: video system not initialized
    • 2.1 Output
  • 3 NameError: name ‘QUIT’ is not defined
  • 4 ModuleNotFoundError: No module named ‘pygame’
  • 5 Pygame error, No video mode has been set

Fix Pygame. error: video system not initialized

According to my search online, most people fail to call pygame.init(). I don’t know why I’m receiving this error. Throughout your game, you haven’t called pygame.init(). This is about the most straightforward program you can write in Pygame. It creates a window and allows you to close it. However, I am getting the following error pygame.error: video system not initialized

It would be best to say that this error occurs when you quit the game. All the pygame modules are uninitialized with pygame. Quit (), but the while loop continues to run, and pygame still runs. The display. update() is called, the video system becomes uninitialized, and errors occur. You can fix this by implementing the following:

pygame.error: video system not initialized

import pygame

running = True

while running:
    pygame.init()
    for event in pygame.event.get():
        if event.type == quit:
            running = False

# When the while loop is complete, uninitialized pygame and exit the program. pygame.quit()

Output

pygame 2.1.0 (SDL 2.0.16, Python 3.6.5)

Hello from the pygame community. https://www.pygame.org/contribute.html

Sys.exit() # import sys at the top of the module.

  • Pygame needs to be initialized using this command pygame. If the problem is not resolved, follow these steps:
  • Using a beta version causes this problem.
  • As a result, I suggest you use the new, old version(if you are using 3.8 Pythons, you need to install Python 3.7)
  • Now run pip install pygame in the python terminal (pip install pygame).
  • The problem has now been resolved.

NameError: name ‘QUIT’ is not defined

Use this word “quit” instead of “QUIT”

There’s no call to pygame. init() anywhere.

Learn about Import and Initialize in the basic Intro tutorial or the specific Import and Initialize tutorial, which explains that Pygame needs to be initialized before doing much with it. You usually need to make one call to do this. pygame.init()

ModuleNotFoundError: No module named ‘pygame’

  • Go to CMD and run this command: pip install pygame.
  • If it will work perfectly then no need to again install.
  • That’s all.

Most of the time you will face this error while running any Python game with the library of Pygame so, be aware of the bugs. Let’s fix it also.

Read More: Way to fix Python indentation

Pygame error, No video mode has been set

You may be getting this error because you don’t have the right video driver installed, or your graphics card isn’t powerful enough to run pygame. You can try updating your video driver or trying a different graphics card.

Уведомления

  • Начало
  • » 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

Понравилась статья? Поделить с друзьями:
  • Putty ssh network error connection refused
  • Pygame error unable to open file
  • Putty permission denied как исправить
  • Putty network error network is unreachable
  • Pygame error text has zero width