(Nov-27-2019, 04:43 AM)tonycstech Wrote: Is this loop specifically for tkinter module and it will run independent from the rest of the code ?
All GUI or web-app(server) has some kind of main loop that run continuous.
If think of it so are these application something that you don't want to stop,before you push eg a stop button.
tonycstech Wrote:is this main loop that runs independent of any modules that are currently running ?
No,if you make loop or something that interfere with the main loop GUI is running it will freeze GUI.
Here a example from doc,i have put in
time.sleep
this will freeze GUI main loop for 10-sec.
A normal way is to have a quit button as here that break GUI main loop.
import tkinter as tk
import time
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello World\n(click me)"
self.hi_there["command"] = self.say_hi
self.hi_there.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=self.master.destroy)
self.quit.pack(side="bottom")
def say_hi(self):
time.sleep(10)
print("hi there, everyone!")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
Usually all GUI's has some kind of methods build in for Threading(Multithreading).
A very common mistake that many makes with GUI is to freeze the main loop not thinking of this.
Tkinter has eg
after
.
Example here dos it print
hello world
every 10-sec,but it dos not freeze GUI as i showed with
time.sleep
.
import tkinter as tk
class Foo(tk.Tk):
def __init__(self):
super().__init__()
self.callId = None
self.button = tk.Button(self, text="Stop", command=self.stop)
self.button.pack()
def periodically_speak(self):
print("Hello world!")
self.callId = self.after(10000, self.periodically_speak)
def stop(self):
if self.callId is not None:
self.after_cancel(self.callId)
foo = Foo()
foo.periodically_speak()