Ways to create widgets

There are two ways to create widgets in Tkinter.

The first way involves creating a widget in one line and then adding the pack() method (or other geometry managers) in the next line, as follows:

my_label = tk.Label(root, text="I am a label widget")my_label.pack()

Alternatively, you can write both the lines together, as follows:

tk.Label(root, text="I am a label widget").pack()

You can either save a reference to the widget created ( my_label, as in the first example), or create a widget without keeping any reference to it (as demonstrated in the second example).

You should ideally keep a reference to the widget in case the widget has to be accessed later on in the program. For instance, this is useful in case you need ...

Get Tkinter GUI Application Development Blueprints - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.