Adding a Widget

Now that you have a window, you can add a widget. Use the tk.Label class to add some text to a window. Create a Label widget with the text "Hello, Tkinter" and assign it to a variable called greeting:

>>> greeting = tk.Label(text="Hello, Tkinter")

The window you created earlier doesn’t change. You just created a Label widget, but you haven’t added it to the window yet. There are several ways to add widgets to a window. Right now, you can use the Label widget’s .pack() method:

>>> greeting.pack()

The window now looks like this:

When you use .pack() to add a widget to a window, Tkinter sizes the window as small as it can while still fully showing the widget. Now type the following:

>>> window.mainloop()

Nothing seems to happen, but notice that a new prompt does not appear in the shell.

window.mainloop() tells Python to run the Tkinter event loop. This method listens for events, such as button clicks or keypresses, and blocks any code that comes after it from running until the window it’s called on is closed. Go ahead and close the window you’ve created, and you’ll see a new prompt displayed in the shell.

Creating a window with Tkinter only takes a couple of lines of code. But blank windows aren’t very useful! In the next section, you’ll learn about some of the widgets available in Tkinter, and how you can customize them to meet your application’s needs.