python - 有人可以用 pygame 帮助我编写用于切换按钮的代码吗?
问题描述
def box_button(x,y, colour, action=None):
toggle = False
pos = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if click[0] == 1 and (x + 10) + 30 > pos[0] > (x + 10) and (y + 10) + 30 > pos[1] > (y + 10):
if toggle == True:
toggle = False
colour = red
else:
toggle = True
colour = green
pygame.draw.rect(window, white, (x, y, 50, 50))
pygame.draw.rect(window, colour, (x + 10, y+10, 30, 30))
return colour
任何人都可以帮助此代码,以便它可以帮助我将按钮从红色切换到绿色?每次我单击带有此代码的按钮时,它都会在我左键单击时变为绿色,但是当我松开单击时,它又变回红色,我希望它永久保持绿色?谢谢
解决方案
click[0] == 1
是 True,只要按钮被按住。您必须实施该MOUSEBUTTONDOWN
事件。
获取主应用程序循环中的事件列表:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
# [...]
添加一个events
参数box_button
并将事件列表传递给函数:
box_button(events, .....)
检查MOUSEBUTTONDOWN
事件box_button
并pygame.Rect
分别collidepoint
用于碰撞测试:
def box_button(events, x, y, colour, action=None):
toggle = False
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN:
button_rect = pygame.Rect(x + 10, y+10, 30, 30)
if event.button == 1 and button_rect.collidepoint(event.pos):
toggle = not toggle
colour = green if toggle else red
pygame.draw.rect(window, white, (x, y, 50, 50))
pygame.draw.rect(window, colour, (x + 10, y+10, 30, 30))
return colour
推荐阅读
- json - 具有原始类型或 $ref 类型的 JSON Schema 对象?
- arrays - 在 Escape Velocity 中将变量设置为数组
- sql - 如何在 SQL Server 中获取字符串前后的所有内容
- scrapy - Tripadvisor 爬取 0 页(0 页/分钟)的 Scrapy 蜘蛛
- amazon-web-services - 如何在 Amazon aws lex 中将响应消息显示为响应卡?
- sql-server - SQL 复制 is_subscribed 标志设置为 1
- spring - java.lang.NoClassDefFoundError: org/springframework/transaction/interceptor/TransactionAttributeSource 升级到 Spring 5 时出错
- javascript - 为什么这被认为是承诺的“良好”保证?
- sulu - 是否可以在安装之间导出和导入内容?
- css - 导航栏子元素忽略 css 规则