我正在制作一个游戏,需要用户根据给定的物种照片键入一个合适的门.我为我的游戏提供了一个GUI.目前,我正在努力限制用户给出答案的时间.我try 了定时器(线程),但idk知道当用户没有超过最大时间时如何取消线程.

  time_answer = 10
    def confirm_action():
        global img_label, answer, n
        from_answer = answer.get().lower()
        if n == len(files) - 1:
            answer_check(from_answer, round_up(end - start, 2))
            confirm.configure(text="Done")
            answer.configure(state=DISABLED)
            n += 1
        elif n == len(files):
            root.quit()
        else:
            answer_check(from_answer, "(Press shift)")
            answer.bind("<Shift_L>", insert_text)
            n += 1
            img_f = ImageTk.PhotoImage(Image.open(f"program_ib_zdjecia/faces/{directories[n]}/{files[n]}"))
            img_label.configure(image=img_f)
            img_label.image = img_f
            t = Timer(time_answer, confirm_action)
            t.start()
    
    confirm = Button(root, text="Confirm", command=confirm_action)

推荐答案

正如@Bryan Oakley所说,您可以使用tkinterafter()方法设置一个计时器,禁用用户输入,但前提是用户在一定时间内没有提交输入.

我会在这里解释,下面是一个简单的例子.


Setting a timer using after()

首先,如何使用after()设置计时器.它有两个论点:

  1. 调用函数之前等待的毫秒数,以及
  2. 该函数在需要时调用.

例如,如果您想在1秒后更改标签的文本,可以执行以下操作:

root.after(1000, lambda: label.config(text="Done!")

Canceling the timer using after_cancel()

现在,如果用户does在给定的时间内提交输入,您将需要某种取消计时器的方法.这就是after_cancel()的意义.需要一个参数:要取消的计时器的字符串id.

要获取计时器的id,需要将返回值after()分配给一个变量.这样地:

timer = root.after(1000, some_function)
root.after_cancel(timer)

实例

下面是一个使用按钮的可取消计时器的简单示例.在按钮被禁用之前,用户有3秒钟的时间按下按钮,如果他们在时间到之前按下按钮,计时器将被取消,这样按钮就永远不会被禁用.

import tkinter

# Create the window and the button
root = tkinter.Tk()
button = tkinter.Button(root, text="Press me before time runs out!")
button.pack()

# The function that disables the button
def disable_button():
    button.config(state="disabled", text="Too late!")

# The timer that disables the button after 3 seconds
timer = root.after(3000, disable_button)

# The function that cancels the timer
def cancel_timer():
    root.after_cancel(timer)

# Set the button's command so that it cancels the timer when it's clicked
button.config(command=cancel_timer)

root.mainloop()

如果你还有任何问题,请告诉我!

Python-3.x相关问答推荐

使用Python请求从特定URL下载图像时出错

谁能解释一下这个带邮编的多功能环路?

命名空间前缀无效

torch.stack([t1, t1, t1], dim=1)与torch.hstack([t1, t1, t1])之间有什么区别?

Django - ValueError:无法将字符串转换为浮点数:''

单击图形时 plotly graph_objects 持久性数据

为什么 mypy 不适用于 sqlalchemy?

如何在 Telethon 中向机器人发送发送表情符号

非拉丁字符的Python正则表达式不起作用

Pandas数据单调行为

预分配一个无列表

多个返回函数的列表理解?

在python中基于列表理解的条件下跳过元素

django.core.exceptions.ImproperlyConfigured

如何使用python将放置在多个嵌套文件夹中的文档移动和重命名为一个新的单个文件夹?

Pruning in Keras

导入父目录进行简要测试

向 Python 函数添加属性的最佳方法

SQLAlchemy:如果不存在则创建模式

字典理解中的操作顺序