ydwb 发表于 2024-8-21 16:20:08

pygame 按钮设置变色

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.surface = font.render(text, True, color)
      self.body = pygame.Rect(self.x, self.y, self.width, self.height)
    def draw(self):
      x_match = pygame.mouse.get_pos() > self.x and pygame.mouse.get_pos() < self.x + self.width
      y_match = pygame.mouse.get_pos() > self.y and pygame.mouse.get_pos() < self.y + self.height
      if x_match and y_match and event.type == pygame.MOUSEBUTTONDOWN :
            self.count += 1
      if self.count % 2 == 0:
            r,g,b=255,255,0
      if self.count % 2 == 1:
            r, g, b = 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))

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("生产线")
    ticks = pygame.time.get_ticks()
    pygame.display.update()
    framerate = pygame.time.Clock()
    while True:
      framerate.tick(30)
      for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
      screen.fill((0, 0, 0))
      btnfj.draw()
      btnsb.draw()
      pygame.display.update()
按钮设置为两种颜色变换,分别代表开、关状态,每点击一次,颜色改变。有时点击时不变色,为什么呢?

FishC 发表于 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 <= self.x + self.width
      y_match = self.y <= event.pos <= 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 小助理,如未能正确解答您的问题,请继续追问。

cjjJasonchen 发表于 2024-8-21 20:50:42

你写的吗


写的挺好的

cjjJasonchen 发表于 2024-8-21 21:07:23

已经改正了,求个正确答案


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.surface = font.render(text, True, color)
      self.body = pygame.Rect(self.x, self.y, self.width, self.height)
    def draw(self):
      x_match = pygame.mouse.get_pos() > self.x and pygame.mouse.get_pos() < self.x + self.width
      y_match = pygame.mouse.get_pos() > self.y and pygame.mouse.get_pos() < self.y + self.height
      for event in events:####
            if x_match and y_match and event.type == pygame.MOUSEBUTTONDOWN :####
                self.count += 1####
      if self.count % 2 == 0:
            r,g,b=255,255,0
      if self.count % 2 == 1:
            r, g, b = 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))

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("生产线")
    ticks = pygame.time.get_ticks()
    pygame.display.update()
    framerate = pygame.time.Clock()
    while True:
      framerate.tick(30)
      events = pygame.event.get() #####
      for event in events:#####
            if event.type == QUIT:
                sys.exit()
      screen.fill((0, 0, 0))
      btnfj.draw()
      btnsb.draw()
      pygame.display.update()



在修改的地方后面加了一排###标出来了


这样修改是因为你上面判断的东西都是event,不是最新的事件,有可能是上一帧留下来的(当按住按钮时你的按钮一直闪烁,造成了松开后按钮颜色不确定的结果),解决方法就是把events拿到上面再迭代一次

我做过类似的ui组件,想要的话可以到下面再和我讲,我找一些发给你(我主页里面pygameGUI1.0的开发日志和教程或许对你有帮助{:10_257:}

祝你好运,求最佳答案

ydwb 发表于 2024-8-22 07:07:14

是考虑到pygame 没有现成的按钮控件而编写的。tkinter 没有描写粒子功能,cocos2d 画线、画圆、画矩形不方便,turtle不方便表述几个同时进行的动作。您的改动很好,谢了!

cjjJasonchen 发表于 2024-8-22 08:30:53

ydwb 发表于 2024-8-22 07:07
是考虑到pygame 没有现成的按钮控件而编写的。tkinter 没有描写粒子功能,cocos2d 画线、画圆、画矩形不方 ...

我这个项目太长了,不知道什么时候才能完成。。。
页: [1]
查看完整版本: pygame 按钮设置变色