如何创建一个在时间限制内激活的功能,除非用户在 python 中输入

How to create a function that activates within a time limit unless user gives input in python

我正在尝试在 tkinter 中创建一个 button ,一旦按下,程序会等待特定时间(此处为 1 秒),如果用户不按下 button 再次执行函数fun()
我怎样才能让它工作?
需要注意的是,button默认执行fun(),也只在第一次执行fun2()

import time
import threading
from tkinter import *

def fun():
    global label
    restart = time.perf_counter()
    label.pack()

def fun2(event, start):
    global restart
    restart = start
    but.unbind("<Button-1>", bind_no)
    t1 = threading.Thread(target = fun3)
    t1.start()

def fun3():
    global restart
    while True:
        while time.perf_counter()-restart<1:
            pass
        label.pack()


root = Tk()

label = Label(root, text="fun")

but = Button(root, text= "Click", command= fun)
bind_no = but.bind("<Button-1>", lambda eff: fun2(eff, time.perf_counter()))
but.pack()


root.mainloop()

您不需要threadingtime;可以使用 tk.after

实现您描述的 delayed/cancel 行为的机制

可能是这样的:

1- 按钮调用 delay_action_fun
2- delay_action_fun 触发回调,将在一秒内调用 fun
3-如果没有再次按下按钮,则执行fun
3.1 - 如果在执行回调之前再次按下按钮,则取消对 fun 的回调。

冲洗并重复。

import tkinter as tk

def fun():
    global call_back
    print('executing fun')
    call_back = None

def delay_action_fun():
    """calls fun to xeq in 1 second, but cancels the callback if
    triggered again within that time period
    """
    global call_back
    print('pressed')
    if call_back is None:
        call_back = root.after(1000, fun)
    else:
        print('cancelling cb')
        root.after_cancel(call_back)
        call_back = None

root = tk.Tk()

call_back = None
tk.Button(root, text= "xeq fun", command=delay_action_fun).pack()

root.mainloop()