我正在制作一款游戲,要求用戶根據給定的物種照片鍵入適當的門。我為我的游戲提供了一個 GUI。目前,我正在努力限制用戶必須給出答案的時間。我嘗試使用 Timer(執行緒),但是當用戶不超過最大時間時,我知道如何取消執行緒。這是用于確認答案的按鈕的代碼:
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)
uj5u.com熱心網友回復:
正如@Bryan Oakley所說,您可以使用tkinter'after()方法設定禁用用戶輸入的計時器,但前提是用戶未在一定時間內提交輸入。
我將在此處進行解釋,并在底部提供一個簡單的示例。
使用設定定時器after()
首先,如何使用after(). 它需要兩個引數:
- 呼叫函式之前等待的毫秒數,以及
- 到時候呼叫的函式。
例如,如果您想在 1 秒后更改標簽的文本,您可以執行以下操作:
root.after(1000, lambda: label.config(text="Done!")
使用取消定時器after_cancel()
現在,如果用戶確實在給定的時間內提交了輸入,您將需要某種方式來取消計時器。這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()
如果您還有任何問題,請告訴我!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/465743.html
