如何在点击Pygame按钮时修改倒计时时钟显示的数字
解决方法
你现在遇到的核心问题是:Text_time 是你进入主循环前就渲染好的固定文本图片,修改total_secs变量后不会自动更新显示,需要手动重新计算时间、重新渲染文本才能生效。
第一步:补全你代码里缺失的基础配置
你现在的代码运行会直接报错,先把缺的内容补上:
- 颜色要赋值具体RGB值
- 字体要先初始化,不能直接用未定义的
font_1、font_2 - 各个按钮的碰撞区域(TextRect_1到TextRect_6)要先定义
- 拼写错误修正:
BLACJ改成BLACK
第二步:实现按钮点击修改时间+刷新显示的逻辑
你只需要在按钮点击的判断里修改total_secs的值,然后每次主循环都重新计算时间、重新渲染时间文本即可,具体修改见下方完整可运行代码:
import pygame pygame.init() screen = pygame.display.set_mode((500,600)) # 补全颜色定义 这里给的是示例RGB值 你可以自己改 GREEN = (34, 197, 94) YELLOW = (234, 179, 8) BLACK = (0,0,0) RED = (239, 68, 68) WHITE = (255,255,255) KIARA = (255, 182, 193) # 这里给的是粉色示例 你可以自己换 # 补全字体定义 第一个参数是字体文件路径 填None用默认字体 第二个是字号 font_1 = pygame.font.Font(None, 60) font_2 = pygame.font.Font(None, 120) # 生成按钮文本 Text_1 = font_1.render('+1分',True,KIARA) Text_2 = font_1.render('+1秒',True,KIARA) Text_3 = font_1.render('-1分',True,KIARA) Text_4 = font_1.render('-1秒',True,KIARA) Text_5 = font_1.render('START',True,BLACK) Text_6 = font_1.render('RESET',True,BLACK) # 补全所有按钮的位置定义 TextRect_1 = Text_1.get_rect(center=(100,100)) TextRect_2 = Text_2.get_rect(center=(200,100)) TextRect_3 = Text_3.get_rect(center=(100,250)) TextRect_4 = Text_4.get_rect(center=(200,250)) TextRect_5 = Text_5.get_rect(center=(100, 500)) TextRect_6 = Text_6.get_rect(center=(300, 500)) total_secs = 0 TextRect_time = None # 先占个位置 后面主循环里更新 running = True while running: screen.fill(GREEN) mouse_x, mouse_y = pygame.mouse.get_pos() # 每次循环都重新计算时间、渲染文本 这样改完total_secs自动更新显示 mins = total_secs // 60 secs = total_secs % 60 # 补个前导零 显示更规范 比如1分5秒显示成01:05而不是1:5 time = f"{mins:02d}:{secs:02d}" Text_time = font_2.render(time,True,BLACK) if TextRect_time is None: TextRect_time = Text_time.get_rect(center=(248,425)) # 绘制所有元素 screen.blit(Text_1,TextRect_1) screen.blit(Text_2,TextRect_2) screen.blit(Text_3,TextRect_3) screen.blit(Text_4,TextRect_4) screen.blit(Text_5,TextRect_5) screen.blit(Text_6,TextRect_6) screen.blit(Text_time,TextRect_time) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: # +1分钟按钮 if TextRect_1.collidepoint(mouse_x, mouse_y): total_secs += 60 # +1秒按钮 if TextRect_2.collidepoint(mouse_x, mouse_y): total_secs += 1 # -1分钟按钮 最小到0 if TextRect_3.collidepoint(mouse_x, mouse_y): total_secs = max(0, total_secs - 60) # -1秒按钮 最小到0 if TextRect_4.collidepoint(mouse_x, mouse_y): total_secs = max(0, total_secs - 1) # 重置按钮 if TextRect_6.collidepoint(mouse_x, mouse_y): total_secs = 0 pygame.display.flip() pygame.quit()
逻辑说明
- 用
collidepoint方法判断鼠标是否点击在按钮上,比你自己写坐标范围判断更准确,后面改按钮位置也不用手动改坐标范围 - 每次主循环都重新计算时间、渲染时间文本,只要修改
total_secs的值,显示会自动更新 - 加了
max(0, 数值)的判断,防止时间变成负数
内容的提问来源于stack exchange,提问作者no DHC
相关产品推荐
相关产品推荐

