在Raspberry Pi上的GPIO引脚发生状态更改后,如何更新pygame中的显示?

2024-04-27 15:41:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我的想法是,我有几个开关连接到Raspberry Pi 3 B+上的GPIO引脚,一旦第一个开关打开,“文本2”就会出现。只有第一个开关接通后,第二个开关才能启动。第二个开关打开后,“文本3”将出现。只有第二个开关接通后,第三个也是最后一个开关才能启动。激活第三个开关后,“文本4”出现

文本以应有的方式显示,但文本在另一个文本上不断闪烁。我怀疑这是因为我在同一个循环中有多个pygame.display.flip(),但我找不到解决这个问题的方法。我基本上可以改变背景颜色,移动到新文本似乎“隐藏”闪烁的地方,但我觉得似乎有一个更理智的解决方案。有人有什么想法可以让我开始吗

以下是相关代码(此处不包括颜色和文本的所有常量):

while running:
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False


if GPIO.input(24) == 1:
        window.fill(white)
        color1 = white
        color2 = black
        color3 = white
        color4 = white
        window.blit(text2, (window_width/2 - 50,window_height/2 - 100))
        pygame.display.flip()
        
        
if GPIO.input(18) == 0:
        color3 = white
        
if GPIO.input(18) == 1: 
        window.fill(white)
        color1 = white#Second puzzle GPIO
        color2 = white
        color3 = black
        color4 = white
        window.blit(text3, (window_width/2 - 50,window_height/2 - 100))
        pygame.display.flip()
        
if GPIO.input(16) == 0:
        color4 = white
        
if GPIO.input(16) == 1: 
        window.fill(white)
        color1 = white
        color2 = white
        color3 = white
        color4 = black
        window.blit(text4, (window_width/2 - 50,window_height/2 - 100))
        pygame.display.flip()

Tags: 文本eventinputgpioifdisplaywindowfill
1条回答
网友
1楼 · 发布于 2024-04-27 15:41:15

正如OP所说,闪烁确实是由对每个循环的多个调用引起的

我认为最好在循环开始时获取GPIO引脚值,然后在单个屏幕绘制代码块中显示状态:

BLACK = ( 0, 0, 0 )

myfont = pygame.font.Font( None, 16 )
text1  = myfont.render( "Unused",  True, BLACK )
text2  = myfont.render( "GPIO-24", True, BLACK )
text3  = myfont.render( "GPIO-18", True, BLACK )
text4  = myfont.render( "GPIO-16", True, BLACK )

# position texts every 100 pixels
text1_rect = text1.get_rect( top_left = (  50, 100 ) )
text2_rect = text2.get_rect( top_left = ( 150, 100 ) )
text3_rect = text3.get_rect( top_left = ( 250, 100 ) )
text4_rect = text4.get_rect( top_left = ( 350, 100 ) )

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Read GPIO Pin values
    gpio_pin16 = GPIO.input( 16 )
    gpio_pin18 = GPIO.input( 18 )
    gpio_pin24 = GPIO.input( 24 )
    
    # Paint the screen
    window.fill(white)
    if ( gpio_pin24 == 1 ):
        window.blit( text2, text2_rect )
    if ( gpio_pin18 == 1 ):
        window.blit( text3, text3_rect )
    if ( gpio_pin16 == 1 ):
        window.blit( text4, text4_rect )
    pygame.display.flip()

pygame.quit()

我没有完整的代码可以使用,所以我只是猜测它应该如何工作。您的现有标签将被绘制到完全相同的位置,这就是为什么标签会相互遮挡

因此,在上面的代码中,我们定义了text2_rect等来正式定位需要绘制文本的位置,并确保良好的布局。如果GPIO引脚高,主循环将绘制文本,否则将使屏幕的该区域为空。不清楚颜色是如何在提供的代码中工作的,所以我忽略了这一点

如果您想让它们在屏幕上自动定位,可以使用x坐标0window_width//4window_width//23*window_width//4

相关问题 更多 >