我编写了一个简单的pygame程序,我使用树莓派lite操作系统(buster)在树莓派CM4上运行。因此,我必须手动安装x,以便pygame可以输出。使用以下命令完成:
sudo apt-get install --no-install-recommends xserver-xorg xinit x11-xserver-utils openbox
我通过在.bash_profile中包含以下内容来启动程序:
[[ -z $DISPLAY && $XDG_VTNR -eq 1 ]] && startx -- -nocursor
以及/etc/xdg/openbox/autostart
中的代码:
# Disable any form of screen saver / screen blanking / power management
xset s off
xset s noblank
xset -dpms
# Allow quitting the X server with CTRL-ATL-Backspace
setxkbmap -option terminate:ctrl_alt_bksp
cd project_dir && python project.py
下面是project_dir/project.py的内容:
import pygame as pg
class Game:
def __init__(self):
pg.init()
self.__clock = pg.time.Clock()
self.__window_size = (1024, 768)
self.__project_size = (392, 291)
self.screen = pg.display.set_mode(self.__window_size, pg.FULLSCREEN)
self.blank_background = pg.transform.scale(pg.image.load("assets/default_background.png"),
self.__window_size).convert()
self.grid_image = pg.transform.scale(pg.image.load("assets/new_project_thumb.png"),
self.__project_size).convert()
self.project_selected = 0
self.rect_pixels = 3
self.grid_locations = self.calculate_grid_locations()
def run(self) -> None:
pg.mouse.set_visible(False)
playing = True
while playing:
events = pg.event.get()
button_event = None
self.screen.blit(self.blank_background, (0, 0))
for event in events:
if event.type == pg.KEYDOWN:
button_event = event.key
if button_event == pg.K_LEFT:
self.project_selected = max((self.project_selected - 1), 0)
if button_event == pg.K_RIGHT:
self.project_selected = min((self.project_selected + 1), 3)
if button_event == pg.K_ESCAPE:
playing = False
self.draw_menu()
pg.display.update()
self.__clock.tick(6)
def draw_menu(self):
for i in range(4):
if i == self.project_selected:
rect_loc = (self.grid_locations[i][0] - self.rect_pixels,
self.grid_locations[i][1] - self.rect_pixels)
pg.draw.rect(self.screen,
(237, 28, 36),
pg.Rect(rect_loc,
(self.__project_size[0] + self.rect_pixels * 2,
self.__project_size[1] + self.rect_pixels * 2)))
self.screen.blit(self.grid_image, self.grid_locations[i])
def calculate_grid_locations(self):
w=int((self.__window_size[0] - 2 * self.__project_size[0]) / 3)
h=int((self.__window_size[1] - 2 * self.__project_size[1]) / 3)
return [(w, h),
(w * 2 + self.__project_size[0], h),
(w, h * 2 + self.__project_size[1]),
(w * 2 + self.__project_size[0], h * 2 + self.__project_size[1])]
if __name__ == "__main__":
game = Game()
game.run()
程序在自动启动时工作得很好,但是如果我在自动启动后使用ctrl-alt-backspace退出程序和x,然后使用python project.py
从命令行重新启动它,则显示在pygame程序的帧之间间歇性闪烁。在我的ubuntu笔记本电脑上运行时不会发生这种情况,只在CM4上运行。
有谁知道这可能是什么原因吗?
弄清楚了——问题是我正在杀死x服务器。如果x服务器被杀死,Python/pygame仍然可以以某种方式输出到屏幕,但性能确实下降了。如果我再次运行startx -- -nocursor
而不是python project.py
,它会再次启动x服务器,并在/etc/xdg/openbox/autostart
中运行整个脚本,作为启动的一部分,这也会导致程序启动。