1

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!

JeffD
  • 71
  • 5
  • 1
    It is a loop. When you have a GUI, the program running it needs to constantly check for events (clicks, mouse movement, resizing, etc). Calling `mainloop` initiates the GUI to begin listening and processing these events. It does this in the background so you don't have to take care of it yourself. – SyntaxVoid Jan 30 '20 at 17:41
  • 2
    Does this answer your question? [Tkinter understanding mainloop](https://stackoverflow.com/questions/29158220/tkinter-understanding-mainloop) -- Read the answer from BryanOakley which I think describes `mainloop` very well. – SyntaxVoid Jan 30 '20 at 17:44
  • I did read that answer from BryanOakley, and it was helpful, but I'm still confused. Is it only the methods that create that GUI that are called during the execution of the loop? Why aren't my x values increasing? – JeffD Jan 30 '20 at 17:49

1 Answers1

2

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685