Search code examples
pythontkintertkinter-button

Why is my button working even though I haven't assigned any parent window to it?


Why is my button working even though I haven't assigned any parent window to it?

from tkinter import *

root = Tk()

Button(text='MyButton').pack()

root.mainloop()

Solution

  • Widgets live in a tree-like hierarchy with a single widget acting as the root of the tree. The root widget is an instance of Tk and should be explicitly created by the application before any other widget.

    All widgets except the root window require a master. If you do not explicitly define the master for a widget it will default to using the root window.

    You can turn this behavior off by calling the function NoDefaultRoot from the tkinter module. For example, the following code will fail with AttributeError: 'NoneType' object has no attribute 'tk':

    from tkinter import *
    
    NoDefaultRoot()
    
    root = Tk()
    Button(text='MyButton').pack() 
    root.mainloop()