sco*_*oth 5 python pygame raspberry-pi
我正在尝试在Raspberry Pi上初始化pygame,它需要键盘中断才能执行任何操作.这是我的代码:
os.putenv ( "SDL_VIDEODRIVER" , "fbcon" )
pygame.display.init() # It hangs here
screen = pygame.display.set_mode ( ( 1024 , 768 ) )
pygame.draw.rect ( screen , ( 0 , 255 , 0 ) , ( 15 , 15 , 15 , 15 ) )
pygame.display.flip()
keyLoop = True
while keyLoop:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
print ( "Down arrow pressed, exiting" )
keyLoop = False
pygame.quit()
Run Code Online (Sandbox Code Playgroud)
我在这里发现了一个类似的问题,Python程序在键盘中断之前不会响应,但它不会让我添加注释,我已经尝试了所有他们的建议但仍然有问题.如果我按CTRL + C然后我的图形出现,但键盘不起作用.
谢谢
编辑
我通过完全删除os.putenv来完成它.问题实际上是在config.txt中的Pi设置中.我试图初始化一个大于Pi的帧缓冲区的pygame显示.确保两个匹配(framebuffer和display.set_mode)使它启动就好了.
小智 7
我有完全相同的问题,但它只会发生在我的pygame代码的第二次运行(即首次运行启动,一切正常,但如果你停止程序然后尝试重新启动它然后挂起pygame.init或pygame.display.set_mode).
来自某人或其他人的解决方案对我不起作用(键盘中断的提升似乎没有触及主线程,只是分叉线程)但是感谢这个想法!得到的工作代码片段如下.
from signal import alarm, signal, SIGALRM, SIGKILL
def init_Pygame():
# this section is an unbelievable nasty hack - for some reason Pygame
# needs a keyboardinterrupt to initialise in some limited circs (second time running)
class Alarm(Exception):
pass
def alarm_handler(signum, frame):
raise Alarm
signal(SIGALRM, alarm_handler)
alarm(3)
try:
pygame.init()
DISPLAYSURFACE = pygame.display.set_mode((DISPLAYWIDTH, DISPLAYHEIGHT))
alarm(0)
except Alarm:
raise KeyboardInterrupt
pygame.display.set_caption('Drawing')
[...rest of initialisation...]
Run Code Online (Sandbox Code Playgroud)
虽然这是一个解决方案,但我不知道导致这种行为的原因.
Pygame.init() 永远不会导致这种情况(除非你实际上在 python 中发现了错误,不太可能),但是 os.putenv() 很可能导致这种情况。这可能无法解决您的问题,但最好在 os.environ 中设置更改,而不是在 os.putenv() 中设置。它在 OSX 上也不起作用,因此如果您在 OSX 上使用它,可能会出现错误。最后一个可能的解决方案是针对您的问题进行修补。这是一个混乱的解决方案,除非您找不到其他任何东西,否则不应该实现,但它会起作用,前提是程序在键盘中断后正常工作。您可以使程序自动引发键盘中断事件。一种方法是启动一个计时器,这将引发键盘中断。唯一的困难是它必须在后台运行才能在必要时引起中断。您可以使用线程模块来执行此操作。这是一个补丁。(记住尽量不要使用这个,它并不理想)
import threading
import time
def timer():
time.sleep(0.5)
raise KeyboardInterrupt
interrupter = threading.Thread(target=timer)
interrupter.start()
os.putenv ( "SDL_VIDEODRIVER" , "fbcon" )
pygame.display.init() # It hangs here
screen = pygame.display.set_mode ( ( 1024 , 768 ) )
pygame.draw.rect ( screen , ( 0 , 255 , 0 ) , ( 15 , 15 , 15 , 15 ) )
pygame.display.flip()
keyLoop = True
while keyLoop:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
print ( "Down arrow pressed, exiting" )
keyLoop = False
pygame.quit()
Run Code Online (Sandbox Code Playgroud)
这应该可以让它发挥作用。
| 归档时间: |
|
| 查看次数: |
3259 次 |
| 最近记录: |