我正在尝试使用PyGame绘制图像,我从Adafruit复制了这段代码。奇怪的是,直到我按Ctrl-C,屏幕上才会显示任何内容,此时它会显示图像。然后图像停留在屏幕上,直到我再次按下Ctrl-C。然后我收到以下消息:
追踪(最近的呼叫最后):
文件“RaspiDisplay.py”,第60行,在 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)
答案 0 :(得分:2)
您没有在任何地方运行事件循环。相反,你只是初始化所有东西,然后进入睡眠状态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
子句。