Home > Enterprise >  Why does this simple Tkinter code create two top-level windows?
Why does this simple Tkinter code create two top-level windows?

Time:01-23

Consider this very simple code snippet:

import tkinter as tk

class GUI:
    def __init__(self):
        self.top_level_window = tk.Tk()
        

GUI()
GUI().top_level_window.mainloop()

It creates two top-level windows on my screen. Why?

I thought the first instance would be immediately garbage collected, so that I would only get one window. I have also tried slightly modified version, which I was sure for would create two separate objects, and thus only one window:

a=GUI()
b=GUI()
b.top_level_window.mainloop()

but I was wrong. And I can't think of a reason.

Any help?

CodePudding user response:

Because you called the class two times.

GUI()
GUI().top_level_window.mainloop()
>>>
GUI().top_level_window.mainloop()

CodePudding user response:

I think that with tkinter, the framework itself keeps hold of instances of GUI objects that you create. This defeats any garbage collection that you might assume is going to happen.

You would need to call .destroy() on any elements you want tkinter to forget.

  • Related