0

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()
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135

1 Answers1

1

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()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Um sorry but what do you mean when you say the root window , does that mean the only window which I have created ? – Ayush Singh Aug 24 '20 at 17:54
  • @AyushSingh: widgets exist in a tree-like hierarchy which must have a single widget as the root. This will be the first instance of `Tk` that is created, either explicitly or implicitly. – Bryan Oakley Aug 24 '20 at 17:55