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

Question:

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()
Asked By: Ayush Singh

||

Answers:

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()
Answered By: Bryan Oakley
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.