I'm getting started in Tkinter and specifically now I'm studying / revising the widget Treeview
.
I study and analyze different programs in this and other forums and a doubt has arisen, and that is that sometimes they instantiate it with self
and others with master
, meaning master
the parent of the container widget, and I understand that this is the correct one, but I am surprised that others , with much more experience, use the form self
. What should be used? The container or the parent?
I have done the test changing self
by master
and in principle it works correctly, but something tells me that it is not the same. One of the two modes must be correct
I give an example:
class Application(ttk.Frame):
def __init__(self, main_window):
super().__init__(main_window)
main_window.title("Explorador de archivos y carpetas")
#self.treeview = ttk.Treeview(self) ##### No deberia ser main_Window???? **ORIGINAL**
self.treeview = ttk.Treeview(main_window)
self.treeview.grid(row=0, column=0, sticky="nsew")
Can someone clarify this doubt for me?
What you should always pass to every widget (includes
StringVar
and other variables) is a reference to the parent widget , period. If no reference is passed the parent will be the main window and this can lead to unexpected problems:The parent widget is the widget that contains our widget to be instantiated.
Ok, now let's see your example. It has a class
Application
that derives fromFrame
and within instances aTreeView
.self
refers to the instance of that class, that is, it is attk.Frame
. The question you should ask yourself is:Where do I want to place my
TreeView
?If you use
main_window
it, you place it in the main window, that is, it is a brother widget of the frameApplication
.If you use you
self
place it insideFrame
which is insidemain_window
.Logic tells us that it
Application
is the base container widget for the entire app and that itTreeview
and every widget in the app should be inside it. The logical thing is to useself
as parent. In fact, it is common to use Frames as a geometric base to structure the different levels of the app.Keep in mind that the geometry handlers, methods
grid
,pack
andplace
, act by locating in the parent widget, it is not the same, therefore locating outside or inside theFrame
.Better an example:
I've used
pack
and two buttons for convenience, but this is irrelevant. I have assigned a green background to the main window and a red one to theFrame
(Application).If we use
main_window
as parent of the first button andself
for the second:If we use
self
for both:If we use
main_window
for both :What do we want him for
Frame
? For that we don't derive fromttk.Frame
and create everything in the main window...