Python 如何单击一个元素,然后使用该元素更改另一个元素
我仍然是python的新手,现在我才刚刚开始使用GUI。现在我在屏幕上有一堆元素,我想知道如何注册对一个元素的点击,然后用它来更改被点击的元素和另一个元素。把它放在上下文中,我正在做一个电灯开关。我会发布我的代码,只要它不太粗Python 如何单击一个元素,然后使用该元素更改另一个元素,python,pygame,Python,Pygame,我仍然是python的新手,现在我才刚刚开始使用GUI。现在我在屏幕上有一堆元素,我想知道如何注册对一个元素的点击,然后用它来更改被点击的元素和另一个元素。把它放在上下文中,我正在做一个电灯开关。我会发布我的代码,只要它不太粗 #Import pygame lib import pygame from pygame.locals import * #Initialize the game pygame.init() width, height = 640, 480 screen = pygam
#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()并检查当前鼠标位置是否在按钮的矩形内 在伪代码中:
check for events
if event is mouseclick
if button.rect.collidepoint(button, mouse_pos)
# player clicked, so...
do something
老实说,创建一个可点击的按钮并不麻烦,但如果您是Python和PyGame新手,这可能有点粗糙