|
发表于 2024-8-21 18:31:49
|
显示全部楼层
哇,以前渔条可没遇到这种按钮变色的小妖怪,不过没关系,本鱼化身计算机教育专家,为你除妖解惑!
我们来一起看看你的代码问题所在。主要问题有两个:
1. 你在`Button`类的`draw()`方法中检查鼠标点击位置的逻辑有些问题。
2. `event`变量在`draw`方法中使用时,是需要传递进来的。
咱们先修正这两个问题,让代码更灵活更强大,顺便避免让妖怪跑出来吓咱们:
- import sys
- import pygame
- from pygame.locals import *
- pygame.font.init()
- font1 = pygame.font.SysFont('kaiti', 25)
- class Button:
- def __init__(self, text, color, x, y, width, height, font, count):
- self.x = x
- self.y = y
- self.count = 0
- self.width = width
- self.height = height
- self.color = color
- self.text = text
- self.font = font
- self.surface = font.render(text, True, color)
- self.body = pygame.Rect(self.x, self.y, self.width, self.height)
- def draw(self, screen):
- r, g, b = (255, 255, 0) if self.count % 2 == 0 else (0, 255, 255)
- pygame.draw.rect(screen, (r, g, b), (self.x + 1, self.y + 1, self.width - 3, self.height - 3), 0)
- screen.blit(self.surface, (self.body.x + (self.body.width - self.surface.get_width()) // 2,
- self.y + (self.body.height - self.surface.get_height()) // 2))
- def check_click(self, event):
- x_match = self.x <= event.pos[0] <= self.x + self.width
- y_match = self.y <= event.pos[1] <= self.y + self.height
- if x_match and y_match and event.type == pygame.MOUSEBUTTONDOWN:
- self.count += 1
- self.surface = self.font.render(self.text, True, self.color) # 更新文字渲染
- btnfj = Button("风机", 'red', 482, 280, 70, 40, font1, 0)
- btnsb = Button("水泵", 'red', 40, 280, 70, 40, font1, 0)
- if __name__ == "__main__":
- pygame.init()
- size = width, height = 800, 600
- screen = pygame.display.set_mode(size)
- pygame.display.set_caption("生产线")
- framerate = pygame.time.Clock()
- while True:
- framerate.tick(30)
- for event in pygame.event.get():
- if event.type == QUIT:
- sys.exit()
- if event.type == pygame.MOUSEBUTTONDOWN:
- btnfj.check_click(event)
- btnsb.check_click(event)
- screen.fill((0, 0, 0))
- btnfj.draw(screen)
- btnsb.draw(screen)
- pygame.display.update()
复制代码
**解释一波加搞笑:**
1. 先初始化按钮信息,包括位置、大小、颜色、文字等。
2. `draw`方法负责绘制按钮,把按钮的这块地画得漂漂亮亮的;如果你点击了按钮,`check_click`方法会把这个点击计数记录下来。
3. 每一次刷新屏幕的时候,`check_click`帮你收集是否点击了按钮,而`draw`方法则根据是否点击来决定切换颜色。
这样子,按钮就乖乖听话啦,每次点击都老实地变色,丝毫不会耍赖皮啦!
希望这个答案能帮你降服按钮妖怪,愉快地继续pygame魔法之旅吧!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|