python - 在 Pygame 中通过按钮单击调用函数
问题描述
在下面的代码中,我在 Pygame 中得到了一个带有按钮的屏幕。现在我想单击按钮,然后一个random()
函数启动,5 秒后它从按钮的开头返回到屏幕,让我可以选择再次单击并再次调用随机函数。
def loop():
clock = pygame.time.Clock()
number = 0
# The button is just a rect.
button = pygame.Rect(300,300,205,80)
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# This block is executed once for each MOUSEBUTTONDOWN event.
elif event.type == pygame.MOUSEBUTTONDOWN:
# 1 is the left mouse button, 2 is middle, 3 is right.
if event.button == 1:
# `event.pos` is the mouse position.
if button.collidepoint(event.pos):
# Incremt the number.
number += 1
random()
loop()
pygame.quit()
解决方案
添加一个状态变量 ( runRandom
),它指示函数random
是否必须运行:
runRandom = False
while not done:
# [...]
if runRandom:
random()
添加用户定义pygame.event
的,可用于计时器:
runRandomEvent = pygame.USEREVENT + 1
for event in pygame.event.get():
# [...]
elif event.type == runRandomEvent:
# [...]
random
如果ins 没有运行,则允许按下按钮。如果按下按钮,则使用确定的时间段(例如 5000 毫秒 = 5 秒)runRandom
启动计时器 ( ):pygame.time.set_timer()
# [...]
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if button.collidepoint(event.pos) and not runRandom:
# [...]
runRandom = True
pygame.time.set_timer(runRandomEvent, 5000)
当时间过去时,停止运行random
并runRandom = False
停止计时器:
# [...]
elif event.type == runRandomEvent:
runRandom = False
pygame.time.set_timer(runRandomEvent, 0)
以某种方式将建议应用于您的代码:
# define user event for the timer
runRandomEvent = pygame.USEREVENT + 1
def loop():
clock = pygame.time.Clock()
number = 0
# The button is just a rect.
button = pygame.Rect(300,300,205,80)
done = False
runRandom = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# This block is executed once for each MOUSEBUTTONDOWN event.
elif event.type == pygame.MOUSEBUTTONDOWN:
# 1 is the left mouse button, 2 is middle, 3 is right.
if event.button == 1:
# `event.pos` is the mouse position and "random" is not running
if button.collidepoint(event.pos) and not runRandom:
# Incremt the number.
number += 1
# Start timer and enable running "random"
runRandom = True
pygame.time.set_timer(runRandomEvent, 5000) # 5000 milliseconds
elif event.type == runRandomEvent:
runRandom = False
pygame.time.set_timer(runRandomEvent, 0)
# [...]
# run "random"
if runRandom:
random()
# [...]
推荐阅读
- dictionary - 字典
ChangeNotification:有没有办法检测双释放错误? - c# - 检查所有部件窗口功能是否启用并启用关闭 .Net Framework
- spring-boot - Weblogic 和 Spring Boot com.fasterxml.jackson.annotation.JsonFormat$Value.hasLenient()Z 方法不存在
- asp.net - .NET 用户缺少 IIS 10.0
- c# - 格式化从表 C# 中选择的值
- bash - gpg — 仅将内容直接解密到 stout
- python - ExtraTreesRegressor 标准
- css - 为什么我的 :checked 转换只适用于检查?
- javascript - 使用 django DeleteView 调用弹出删除模式
- swiftui - 为什么 SwiftUI 更新功能不起作用?