我对python仍然是一个菜鸟,现在我才刚开始使用我的GUI。现在,我在屏幕上有一堆元素,我想知道如何注册一个元素的点击,然后使用它来更改被单击的元素和另一个元素。为了说明这一点,我正在做一个电灯开关。我将发布我目前为止不太笨拙的代码。

#Import pygame lib
import pygame
from pygame.locals import *

#Initialize the game
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))

#Load images
switchOn = pygame.image.load("resources/img/switchOn.png")
switchOff = pygame.image.load("resources/img/switchOff.png")
bulbOn = pygame.image.load("resources/img/bulbOn.png")
bulbOff = pygame.image.load("resources/img/bulbOff.png")

#Loop
while 1:
    #clear screen before drawing again
    screen.fill(0)
    #draw the screen elements
    screen.blit(bulbOff, (50,50))
    screen.blit(switchOff, (300,250))
    #update the screen
    pygame.display.flip()
    #loop the events
    for event in pygame.event.get():
        #check if event is X button
        if event.type==pygame.QUIT:
            pygame.quit()
            exit(0)

最佳答案

要注册某个按钮的点击,例如,您需要使用pygame.Rect.collidepoint(http://pygame.org/docs/ref/rect.html#pygame.Rect.collidepoint)并检查当前鼠标位置是否在按钮矩形内。

用伪代码:

check for events
    if event is mouseclick
        if button.rect.collidepoint(button, mouse_pos)
            # player clicked, so...
            do something


老实说,创建​​一个可单击的按钮并不麻烦,但是如果您是Python和PyGame的新手,则可能会有些麻烦。

关于python - 如何单击一个元素,然后使用它来更改另一个元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21112283/

10-14 19:01
查看更多