Florent Florent - 1 year ago 64
Python Question

Is it ok to create and place a tkinter widget at the same time?

I am new in Python and in tkinter so the question may seems naive: is it ok to create and place widgets at the same time if I don't need to change them?
It works but is it a good practice? And if not why?

An example of what I mean:

import tkinter as tk
tk.Label(window,text='Lost Label').pack()

Answer Source

To expand upon @Skynet's answer....

Whenever you do Widget(*args, **kwargs).pack() the pack() method returns None as would other geometry managers, so if you tried to assign this to a variable the variable would be None.

In this case then probably not, since you probably actually want to be storing the reference to the widget.

If you don't need a reference then there's not really a problem with it. As the other answer notes you don't need a definitve reference to every single widget in your GUI unless you plan to use this reference in some way. Unless I plan on changing the label text / modifying it in someway then I typically use your method to save some space. No need to write more code than you have to!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download