我正在嘗試撰寫一個程式來幫助我練習詞匯。基本上我想讓它每 30 分鐘顯示一個視窗,其中包含我當前正在學習的單詞。這是我的代碼:
import time
from tkinter import *
window = Tk()
date = time.ctime()
text = Text(window, width=40, height=10)
window.title("Active Recall Trainer")
text.insert("1.0", "here is my text to insert")
canvas = Canvas(window, width=750, height=500, bg="SpringGreen2")
window.configure(width=300, height=150)
canvas.create_text(30, 10, text="""VOCABULARY""", fill="red")
while True:
time.sleep(60*30)
window.mainloop()
print("Loop Complete")
這段代碼的問題是我的while True回圈只顯示一次視窗并且在它運行時(視窗,而不是回圈),它不能前進到print函式。只有在我關閉回圈行程的視窗后,但正如我之前所說,它不會再重新打開視窗(它會直接列印)。
從我在網上閱讀的內容來看,問題似乎出在mainloop()呼叫中,因為它本質上是在回圈中創建回圈。現在,我的問題是:還有其他使用 tkinter 顯示視窗的方法嗎?如果沒有,有沒有辦法讓它按照使用該方法所解釋的那樣作業?
我將非常感謝任何提示和解決方案。請注意,我對 python 的了解仍然很差,我可能無法理解更復雜的術語,所以請像我 4 歲一樣跟我說話。
編輯:我嘗試在每個回圈結束時關閉視窗,但這似乎也不起作用。我嘗試了兩者quit()和destroy()功能,但都不起作用。使用 destroy 函式時,我的 powershell 回傳:
PS C:\Users\PC> py ex36.py
End of the loop
Traceback (most recent call last):
File "C:\Users\PC\ex36.py", line 43, in <module>
window.destroy()
File "C:\Program Files\Python311\Lib\tkinter\__init__.py", line 2368, in destroy
self.tk.call('destroy', self._w)
_tkinter.TclError: can't invoke "destroy" command: application has been destroyed
而如果我嘗試使用該quit()功能,回圈會繼續進行但在關閉視窗后不會再次重新打開視窗。
編輯 2:解決了!
import time
from tkinter import *
window = Tk()
while True:
window = Tk()
# Window
text = Text(window, width=40, height=10)
window.title("Active Recall Trainer")
text.insert("1.0", "here is my text to insert")
canvas = Canvas(window, width=750, height=500, bg="SpringGreen2")
window.configure(width=300, height=150)
# TEXT
canvas.create_text(30, 10, text="""VOCABULARY""", fill="red")
window.configure(bg="lightgray")
canvas.pack()
# Window
window.after(3000, window.mainloop())
window.after(1000, window.quit())
uj5u.com熱心網友回復:
我也是 python 的新手,從未接觸過 tkinter。如果將所有行都放在 while 回圈中,代碼將按預期作業。這有什么缺點嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/533594.html
