[英]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()
你不需要threading
或time
; 實現您描述的延遲/取消行為的機制可以使用tk.after
實現
也許是這樣的:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.