鱼C论坛

 找回密码
 立即注册
查看: 516|回复: 5

[技术交流] pygame 按钮设置变色

[复制链接]
发表于 2024-8-21 16:20:08 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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()[0] > self.x and pygame.mouse.get_pos()[0] < self.x + self.width
        y_match = pygame.mouse.get_pos()[1] > self.y and pygame.mouse.get_pos()[1] < 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()
按钮设置为两种颜色变换,分别代表开、关状态,每点击一次,颜色改变。有时点击时不变色,为什么呢?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-8-21 18:31:49 | 显示全部楼层
哇,以前渔条可没遇到这种按钮变色的小妖怪,不过没关系,本鱼化身计算机教育专家,为你除妖解惑!

我们来一起看看你的代码问题所在。主要问题有两个:
1. 你在`Button`类的`draw()`方法中检查鼠标点击位置的逻辑有些问题。
2. `event`变量在`draw`方法中使用时,是需要传递进来的。

咱们先修正这两个问题,让代码更灵活更强大,顺便避免让妖怪跑出来吓咱们:

  1. import sys
  2. import pygame
  3. from pygame.locals import *

  4. pygame.font.init()
  5. font1 = pygame.font.SysFont('kaiti', 25)

  6. class Button:
  7.     def __init__(self, text, color, x, y, width, height, font, count):
  8.         self.x = x
  9.         self.y = y
  10.         self.count = 0
  11.         self.width = width
  12.         self.height = height
  13.         self.color = color
  14.         self.text = text
  15.         self.font = font
  16.         self.surface = font.render(text, True, color)
  17.         self.body = pygame.Rect(self.x, self.y, self.width, self.height)

  18.     def draw(self, screen):
  19.         r, g, b = (255, 255, 0) if self.count % 2 == 0 else (0, 255, 255)
  20.         pygame.draw.rect(screen, (r, g, b), (self.x + 1, self.y + 1, self.width - 3, self.height - 3), 0)
  21.         screen.blit(self.surface, (self.body.x + (self.body.width - self.surface.get_width()) // 2,
  22.                                    self.y + (self.body.height - self.surface.get_height()) // 2))

  23.     def check_click(self, event):
  24.         x_match = self.x <= event.pos[0] <= self.x + self.width
  25.         y_match = self.y <= event.pos[1] <= self.y + self.height
  26.         if x_match and y_match and event.type == pygame.MOUSEBUTTONDOWN:
  27.             self.count += 1
  28.             self.surface = self.font.render(self.text, True, self.color)  # 更新文字渲染

  29. btnfj = Button("风机", 'red', 482, 280, 70, 40, font1, 0)
  30. btnsb = Button("水泵", 'red', 40, 280, 70, 40, font1, 0)

  31. if __name__ == "__main__":
  32.     pygame.init()
  33.     size = width, height = 800, 600
  34.     screen = pygame.display.set_mode(size)
  35.     pygame.display.set_caption("生产线")
  36.     framerate = pygame.time.Clock()

  37.     while True:
  38.         framerate.tick(30)
  39.         for event in pygame.event.get():
  40.             if event.type == QUIT:
  41.                 sys.exit()
  42.             if event.type == pygame.MOUSEBUTTONDOWN:
  43.                 btnfj.check_click(event)
  44.                 btnsb.check_click(event)

  45.         screen.fill((0, 0, 0))
  46.         btnfj.draw(screen)
  47.         btnsb.draw(screen)
  48.         pygame.display.update()
复制代码


**解释一波加搞笑:**
1. 先初始化按钮信息,包括位置、大小、颜色、文字等。
2. `draw`方法负责绘制按钮,把按钮的这块地画得漂漂亮亮的;如果你点击了按钮,`check_click`方法会把这个点击计数记录下来。
3. 每一次刷新屏幕的时候,`check_click`帮你收集是否点击了按钮,而`draw`方法则根据是否点击来决定切换颜色。

这样子,按钮就乖乖听话啦,每次点击都老实地变色,丝毫不会耍赖皮啦!

希望这个答案能帮你降服按钮妖怪,愉快地继续pygame魔法之旅吧!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-8-21 20:50:42 | 显示全部楼层
你写的吗


写的挺好的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-8-21 21:07:23 | 显示全部楼层
已经改正了,求个正确答案


  1. import sys
  2. import pygame
  3. from pygame.locals import *
  4. pygame.font.init()
  5. font1 = pygame.font.SysFont('kaiti', 25)
  6. class Button:
  7.     def __init__(self,text,color,x,y,width,height,font,count):
  8.         self.x = x
  9.         self.y = y
  10.         self.count=0
  11.         self.width = width
  12.         self.height = height
  13.         self.surface = font.render(text, True, color)
  14.         self.body = pygame.Rect(self.x, self.y, self.width, self.height)
  15.     def draw(self):
  16.         x_match = pygame.mouse.get_pos()[0] > self.x and pygame.mouse.get_pos()[0] < self.x + self.width
  17.         y_match = pygame.mouse.get_pos()[1] > self.y and pygame.mouse.get_pos()[1] < self.y + self.height
  18.         for event in events:####
  19.             if x_match and y_match and event.type == pygame.MOUSEBUTTONDOWN :####
  20.                 self.count += 1####
  21.         if self.count % 2 == 0:
  22.             r,g,b=255,255,0
  23.         if self.count % 2 == 1:
  24.             r, g, b = 0, 255, 255
  25.         pygame.draw.rect(screen, (r, g, b), (self.x + 1, self.y + 1, self.width - 3, self.height - 3), 0)
  26.         screen.blit(self.surface, (self.body.x + (self.body.width - self.surface.get_width()) // 2,
  27.                                    self.y + (self.body.height - self.surface.get_height()) // 2))

  28. btnfj=Button("风机",'red',482,280,70,40,font1,0)
  29. btnsb=Button("水泵",'red',40,280,70,40,font1,0)
  30. if __name__ == "__main__":
  31.     pygame.init()
  32.     size = width, height =800, 600
  33.     screen = pygame.display.set_mode(size)
  34.     pygame.display.set_caption("生产线")
  35.     ticks = pygame.time.get_ticks()
  36.     pygame.display.update()
  37.     framerate = pygame.time.Clock()
  38.     while True:
  39.         framerate.tick(30)
  40.         events = pygame.event.get() #####
  41.         for event in events:  #####
  42.             if event.type == QUIT:
  43.                 sys.exit()
  44.         screen.fill((0, 0, 0))
  45.         btnfj.draw()
  46.         btnsb.draw()
  47.         pygame.display.update()
复制代码



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


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

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

祝你好运,求最佳答案
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-8-22 07:07:14 | 显示全部楼层
是考虑到pygame 没有现成的按钮控件而编写的。tkinter 没有描写粒子功能,cocos2d 画线、画圆、画矩形不方便,turtle不方便表述几个同时进行的动作。您的改动很好,谢了!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-8-22 08:30:53 From FishC Mobile | 显示全部楼层
ydwb 发表于 2024-8-22 07:07
是考虑到pygame 没有现成的按钮控件而编写的。tkinter 没有描写粒子功能,cocos2d 画线、画圆、画矩形不方 ...

我这个项目太长了,不知道什么时候才能完成。。。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-11 18:14

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表