I am trying to write a program that would help me practice my vocabulary. Basically I want to have it display a window once every 30 minutes which contains the words i'm currently learning. Here's my code:
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")
The problem i have with this code is that my while True
loop only displays the window once and while it's running(the window, not the loop), it can't progress forward to the print
function. It's only once i close the window that the loop progresses, but as i said before, it doesn't reopen the window ever again (it's going straight to print).
From what i read online the problem appears to be within the mainloop()
call as it essentially creates a loop within a loop. Now, my question is that:
Are the any other ways of displaying a window using tkinter?
If not, is there a way to make it work as explained using that method?
I will be extremely grateful for any tips and solutions. Please note that my knowledge of python is still very poor and I might not understand the more complex terms, so please speak to me like i'm 4.
EDIT: I tried closing the window at the end of each loop, but that doesn't seem to work either. I tried both quit()
and destroy()
functions but neither works. When using destroy function, my powershell returns this:
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
whereas if i try using the quit()
function, the loop keeps on going but doesn't ever reopen the window again after closing it.
EDIT 2: SOLVED!
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())
CodePudding user response:
Im also new to python and never touched tkinter. The code works as intended if you place all lines inside the while loop. Any downside to this?