我使用 pygame raspberry pi 和 adafruit tft screen 来显示内容。
#!/usr/bin/python
from subprocess import *
from numpy import genfromtxt
import pygame
from pygame.locals import *
import os
import time
from time import strftime
#from pygame.locals import*
#from matplotlib.dates import DateFormatter
import RPi.GPIO as GPIO
import datetime
def run_cmd(cmd):
"""Used to run Linux commands"""
p = Popen(cmd, shell=True, stdout=PIPE)
output = p.communicate()[0]
return output
def displayText(text, size, line, color, clearScreen):
"""Used to display text to the screen. displayText is only configured to display
two lines on the TFT. Only clear screen when writing the first line"""
if clearScreen:
screen.fill((0, 0, 0))
font = pygame.font.Font(None, size)
text = font.render(text, 0, color)
textRotated = pygame.transform.rotate(text, -90)
textpos = textRotated.get_rect()
textpos.centery = 80
if line == 1:
textpos.centerx = 90
screen.blit(textRotated,textpos)
elif line == 2:
textpos.centerx = 40
screen.blit(textRotated,textpos)
def displayTime():
"""Used to display date and time on the TFT"""
screen.fill((0, 0, 0))
font = pygame.font.Font(None, 50)
now=time.localtime()
for setting in [("%H:%M:%S",60),("%d %b",10)] :
timeformat,dim=setting
currentTimeLine = strftime(timeformat, now)
text = font.render(currentTimeLine, 0, (0,250,150))
Surf = pygame.transform.rotate(text, -90)
screen.blit(Surf,(dim,20))
def main():
global ax,fig,screen
global firstTime,lines
global TwentyFourHours,TwelveHours,OneWeek
global dataFile
size = width, height = 128, 160
TFTxSize = 2.28
TFTySize = 1.63
TwentyFourHours = 288
TwelveHours = 144
OneWeek = 2016
firstTime = True #Used to work out if a function has already been run
whatToDisplay = 1 #What do display on screen
rotate = 0 #Used when automatically rotating the display.
startTime = time.time() #Used to work out how much time has passed when rotating.
#Set the framebuffer device to be the TFT
os.environ["SDL_FBDEV"] = "/dev/fb1"
#Setup pygame display
pygame.init()
pygame.mouse.set_visible(0)
screen = pygame.display.set_mode(size)
try:
while True:
time.sleep(.5)
firstTime = True #If button pressed, set this to True
if whatToDisplay == 1: #Display time
displayTime()
elif whatToDisplay == 2: #Display last temperature recorded.
displayText('Current Temp', True )
elif whatToDisplay == 3: #Rotate display
elapsedTime = time.time() - startTime
#Write to TFT
pygame.display.flip()
except KeyboardInterrupt:
pygame.quit()
sys.exit()
if __name__ == '__main__':
main()
按 ^C 不会关闭屏幕显示,也不会返回控制台。 我必须重新启动 pi,这对于测试东西来说非常痛苦。 显示效果很好,当我可以正确关闭它时,我将解决任何其他问题。
最佳答案
如果按键由 pygame 处理,则
KeyboardInterrupt
将不会启动。以下是检测 CTRL + C 事件的方法。
while True:
for event in pygame.event.get():
if (event.type == pygame.KEYUP and event.key == pygame.K_c and
event.mod & pygame.KMOD_CTRL):
pygame.quit()
sys.exit()
:)
关于python - pygame 未关闭并返回控制台(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32673819/