pygame.error:使用线程时,视频系统未初始化



最近我完成了对python中线程的学习,现在正试图在程序中实现它。这是代码:

from threading import Thread
from time import sleep
import pygame as py
py.init()
X,Y = 900, 800
APP = py.display.set_mode((X, Y))
APP = py.display.set_caption("Test")
def exit_app():
"To terminate program."
while True:
for eve in py.event.get():
if eve.type == py.QUIT:
py.quit()
exit()
def update_display():
"Update pygame window"
while True:
sleep(3)
py.display.update()
if __name__ == "__main__":
Thread(target=exit_app).start()
Thread(target=update_display).start()

现在的问题是,在创建线程后,我遇到了一个问题。当我试图运行代码时,它被执行时没有任何问题,但当代码退出时(即,当我关闭pygame窗口时(,我看到的错误如下:

$python3 test.py
pygame 2.0.1 (SDL 2.0.14, Python 3.9.4)
Hello from the pygame community. https://www.pygame.org/contribute.html
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
self.run()
File "/usr/lib/python3.9/threading.py", line 892, in run
self._target(*self._args, **self._kwargs)
File "/home/cvam/Documents/test.py", line 23, in update_display
py.display.update()
pygame.error: video system not initialized      

好的,所以首先,您似乎正在尝试创建具有无限循环的单独函数,用于更新屏幕和事件处理,为了清除相同的内容,所有这些都可以在一个循环中完成,这可能是更好的方法。[因此,我删除了exit_app和update_display函数,因为它们使用了另外两个无限while循环。]

其次,没有必要使用单独的线程来处理事件,因为事件处理可以在同一个循环中完成,当你用一个无限while循环为它创建一个单独的线程时,这会导致pygame应该在哪个线程上运行,主线程还是THREAD1。[因此,这一点已经被注释掉了。]

此外,将pygame.init函数调用和之前在外部的所有其他语句放在ifname=='main'块内似乎可以确保它们被执行。将它们放在线程启动之前也可以确保它们被执行,并且pygame的东西在线程执行之前被初始化。

还有一些建议-:

  • 可以使用pygame时间模块的类似功能,即pygame.time.delay功能,而不是时间模块的睡眠功能,它存在于pygame中,因此更适合使用。

  • 我在使用内置的退出和退出函数退出pygame程序时遇到了很多错误,因此我似乎更喜欢使用python的sys模块的退出函数,因为在大多数情况下,它会减少错误。

相同的代码应变为-:

# from threading import Thread
# from time import sleep
import pygame
import sys
if __name__ == "__main__":
pygame.init()
X,Y = 900, 800
APP = pygame.display.set_mode((X, Y))
APP = pygame.display.set_caption("Test")

# # By detecting the events within the main game loop there is no need
# # to call a separate thread, and the same may not be working since the two
# # threads the main one and the THREAD1 are both containing infinite loops and pygame
# # can only take over one at a time.
# THREAD1=Thread(target=exit_app)
# THREAD1.start()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit() # sys module's exit method seems to be better and causes less errors at exit

# # Without a delay the window will still not close incase this script is being
# # used for that purpose by you.
# pygame.time.delay(3) # Pygame alternative to sleep method of time module https://www.pygame.org/docs/ref/time.html#pygame.time.delay
pygame.display.update()
continue

pass

最新更新