Search code examples
pythonpython-3.xtkintermainloop

Is tkinter's mainloop() function actually a loop?


Thank you for you patience with another newbie question. I am learning tkinter and I am confused about the mainloop(). What exactly is looping? For example:

import tkinter as tk
class Test(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()
        x = 2
        x += 1
        print(x)
    def create_widgets(self):
        y = 1
        y += 1
        print(y)


root = tk.Tk()
app = Test(master=root)
app.mainloop()

If this program was looping through class Test (or either of the functions), my console should keep printing increasing x and y values. Of course, it doesn't. It simply prints x and y one time.

Thank you for your the help!


Solution

  • I am confused about the mainloop(). What exactly is looping?

    Tkinter maintains a queue of events. mainloop loops over that queue, pulling items off and executing functions bound to the events.

    If this program was looping through class Test ...

    It doesn't loop through your code. There is an internal, constantly updating list of events. mainloop loops over that list. It doesn't loop over your code.