Building Your First GUI App

00:00 Building Your First GUI Application With tkinter The foundational element of a tkinter GUI is the window. Windows are the containers in which all other GUI elements live.

00:13 These other elements, such as text boxes, labels, and buttons, are known as widgets and widgets are contained inside of windows. First, you’ll want to create a window that contains a single widget.

00:26 Open up a new Python shell session and follow along. With the Python shell open, the first thing to do is to import tkinter using the standard alias of tk.

00:38 A window is an instance of tkinter’s tk class. Go ahead and create a new window and assign it to the variable window.

00:49 When you execute the code, a new window will pop up on your screen.

00:54 How it looks will depend on your operating system. Throughout the rest of the course, you’ll see the code running on macOS. Now that you have a window, you can add a widget.

01:05 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.

01:21 You may note that the window you created earlier doesn’t change. You’ve created a label widget, but you haven’t added it to the window yet. There are several ways to add widgets to a window, but right now you’ll use the pack() method.

01:37 The window now has the text in it. When you pack a widget into a window, tkinter sizes the window as small as it can be while still encompassing the widget.

01:48 Now execute the next line.

01:52 Nothing seems to happen, but notice that no new prompt appears in your shell. window mainloop() tells Python to run the tkinter event loop.

02:02 This method listens for events such as button clicks and key presses and blocks any code that comes after it from running until you close the window where you called the method.

02:13 Close the window you’ve created and you’ll see a new prompt appear in the shell.

02:20 One thing to note is when you work with tkinter from the REPL, updates to windows are applied as each line is executed. But this is not the case when a tkinter program is executed from a Python file.

02:32 If you don’t include window.mainloop() at the end of a program in a Python file, then the tkinter application will never run, so nothing will be displayed.

02:42 Creating a window with tkinter only takes a couple of lines of code, but blank windows aren’t very useful. So in the next section of the course, you’ll learn about some of the widgets available in tkinter and how you can customize them to meet your application’s needs.

Become a Member to join the conversation.