import pygame as pg
import sys
pg.init()
buttonGray2 = pg.Color('gray50')
textColour = pg.Color('navy')
buttonFont = pg.font.SysFont("garamond", 25)
screen = pg.display.set_mode((400, 400))
clock = pg.time.Clock()
class Button(pg.sprite.Sprite):
def __init__(self, text, x, y, width, height, colour, enabled):
super().__init__()
self.image = pg.Surface((width, height))
self.image.fill(colour)
self.rect = self.image.get_rect()
txt = buttonFont.render(text, True, textColour)
txtRect = txt.get_rect(center = self.rect.center)
self.image.blit(txt, txtRect)
self.rect.topleft = x, y
self.enabled = True
def isPressed(self, event):
if self.enabled == True:
if event.type == pg.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
return True
return False
Button1 = Button('Button1', 100, 100, 120, 50, buttonGray2,True)
Button2 = Button('Button2',100,200,120,50,buttonGray2,False)
buttonsGroup = pg.sprite.Group(Button1,Button2)
screen.fill((255,255,255))
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit()
elif Button1.isPressed(event):
print("Button1")
elif Button2.isPressed(event):
print("Button2")
buttonsGroup.draw(screen)
pg.display.flip()
clock.tick(60)
以上是我程序中按钮的代码。我尝试添加一个启用的属性,以便在用户完成某些操作后,它会禁用该按钮,禁止isPressed
方法工作。
但是,出于某种原因,当我将false
作为按钮的特征传递时,它仍然有效。所以,我认为我在课堂上做错了什么。
有人能看出我哪里出错吗?
提前致谢!