我正在尝试使用 PyGame 绘制图像,并且我从 Adafruit 复制了此代码。很奇怪,屏幕上似乎没有显示任何内容,直到我按下 Ctrl-C,此时它才显示图像。然后图像将保留在屏幕上,直到我再次按 Ctrl-C。然后我收到以下消息:
Traceback (most recent call last):
File "RaspiDisplay.py", line 60, in
time.sleep(10)
KeyboardInterrupt
发生什么事了?顺便说一句,我在树莓派上通过 ssh 运行这个,显示设置为 0(我的电视)如果我在 init 中放置一条打印语句,直到我按Ctrl-C。
import os
import pygame
import time
import random
class pyscope :
screen = None;
def __init__(self):
"Ininitializes a new pygame screen using the framebuffer"
# Based on "Python GUI in Linux frame buffer"
# http://www.karoltomala.com/blog/?p=679
disp_no = os.getenv("DISPLAY")
if disp_no:
print "I'm running under X display = {0}".format(disp_no)
# Check which frame buffer drivers are available
# Start with fbcon since directfb hangs with composite output
drivers = ['fbcon', 'directfb', 'svgalib']
found = False
for driver in drivers:
# Make sure that SDL_VIDEODRIVER is set
if not os.getenv('SDL_VIDEODRIVER'):
os.putenv('SDL_VIDEODRIVER', driver)
try:
pygame.display.init()
except pygame.error:
print 'Driver: {0} failed.'.format(driver)
continue
found = True
break
if not found:
raise Exception('No suitable video driver found!')
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
print "Framebuffer size: %d x %d" % (size[0], size[1])
self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
# Clear the screen to start
self.screen.fill((0, 0, 0))
# Initialise font support
pygame.font.init()
# Render the screen
pygame.display.update()
def __del__(self):
"Destructor to make sure pygame shuts down, etc."
def test(self):
# Fill the screen with red (255, 0, 0)
red = (255, 0, 0)
self.screen.fill(red)
# Update the display
pygame.display.update()
# Create an instance of the PyScope class
scope = pyscope()
scope.test()
time.sleep(10)
最佳答案
您没有在任何地方运行事件循环。相反,您只需初始化所有内容,然后休眠 10 秒钟。在那 10 秒内,您的代码没有执行任何操作,因为这就是您告诉它执行的操作。这意味着无需更新屏幕、响应鼠标点击或其他任何操作。
有几种不同的方法来驱动 pygame,但最简单的是这样的:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
# any other event handling you need
# all the idle-time stuff you want to do each frame
# usually ending with pygame.display.update() or .flip()
请参阅tutorial了解更多信息。
<小时/>附带说明一下,您的初始化代码有很多问题。您迭代了三个驱动程序,但仅设置了 SDL_VIDEODRIVER
一次,因此您只需连续尝试 'fbcon'
三次。另外,你有代码来检测 X 显示,但你不允许 pygame/SDL 使用 X,所以......无论你试图在那里做什么,你都没有这样做。最后,在 Python for 循环中不需要 found
标志;只需使用 else
子句即可。
关于Python程序直到键盘中断才会响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16879810/