【问题标题】:Why is pygame button not functioning?为什么pygame按钮不起作用?
【发布时间】:2021-06-06 08:01:00
【问题描述】:

我一直在遵循Sentdex 的教程来创建一个按钮并使其发挥作用。我试图根据我的要求改变它。当我单击按钮时,我希望执行该功能(另一个屏幕)。我在功能(另一个屏幕)中放置了一个按钮,我可以在其中返回主页。但是当我点击按钮时,它只有在我点击鼠标时才会转到另一个功能,并且在我点击鼠标之前会显示输出。它不会转到另一个屏幕并继续停留在初始屏幕。

import pygame
window = pygame.display.set_mode((1500, 800), pygame.RESIZABLE)

def text_objects(text, font):
    textSurface = font.render(text, True, (0,0,0))
    return textSurface, textSurface.get_rect()

def button(msg, x, y, w, h, ic, ac, action):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(window, ac, (x, y, w, h))
        if click[0] == 1:
            action()
    else:
        pygame.draw.rect(window, ic, (x, y, w, h))
    smallText = pygame.font.SysFont(None, 20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ((x+(w/2)), (y+(h/2)))
    window.blit(textSurf, textRect)

def home_intro():
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                 
        window.blit(image, (0,0))
        pygame.display.set_caption("PROGRAM")
        button("Start", 150, 450, 100, 50, (0,200,0), (255,255,210), start)
        button("Stop", 550, 450, 100, 50, (0,200,0), (255,255,210), stop)
        pygame.display.flip()


home_intro()
pygame.quit()
quit()

我已按照教程进行了所有操作。但我不明白为什么它不起作用。我该如何解决这个问题?

【问题讨论】:

    标签: python button pygame


    【解决方案1】:

    您必须添加一个存储游戏当前状态的变量 (game_state )。单击按钮时更改变量并根据变量的状态绘制不同的场景:

    game_state = "stop"
    
    def start():
        global game_state
        game_state = "start" 
    
    def stop():
        global game_state
        game_state = "stop"
    
    def home_intro():
        global game_state
    
        run = True
        while run:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
                     
            window.blit(image, (0,0))
            button("Start", 150, 450, 100, 50, (0,200,0), (255,255,210), start)
            button("Stop", 550, 450, 100, 50, (0,200,0), (255,255,210), stop)
    
            if game_state == "start":
                # [...]
    
            else:
                # [...]
    
            pygame.display.flip()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      • 2013-01-06
      • 2011-08-14
      • 2017-09-18
      • 1970-01-01
      相关资源
      最近更新 更多