我正在嘗試實作一個文本小部件,tkinter其中只允許在指定時間(此處為 5 秒)輸入文本,然后捕獲鍵入的文本,而不使用呼叫函式的提交按鈕。
我希望時間在用戶開始輸入后立即開始,并且應在 5 秒后阻止用戶再輸入。到目前為止輸入的文本將被顯示。
我嘗試了以下不起作用的代碼。我嘗試查看檔案并進行了網路搜索和許多stackoverflow討論執行緒。我找不到答案。感謝對解決方案的投入。
from tkinter import *
my_window = Tk()
type_txt = Text()
type_txt.grid(row=0, column=0)
type_txt.focus()
type_txt.after(5000, type_txt.configure(state=DISABLED))
typed_text = type_txt.get("1.0", END)
print(typed_text)
my_window.mainloop()
uj5u.com熱心網友回復:
您可以將<key>事件系結到一個函式,然后在回呼中使用 5 秒后禁用文本框.after()。
from tkinter import *
my_window = Tk()
type_txt = Text()
type_txt.grid(row=0, column=0)
type_txt.focus()
def disable_textbox():
type_txt.configure(state=DISABLED)
typed_text = type_txt.get("1.0", END)
print(typed_text)
def start_typing(event):
# disable <Key> binding
type_txt.unbind('<Key>')
# disable text box 5 seconds later
type_txt.after(5000, disable_textbox)
type_txt.bind('<Key>', start_typing)
my_window.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/456968.html
標籤:python-3.x tkinter 时间 文本小部件
下一篇:如何檢查頂層視窗是否打開?
