Join Barron Stone for an in-depth discussion in this video Saying hello to Tkinter, part of Python GUI Development with Tkinter.
Now, that we've verified that Tkl/TK and the TKinter module are installed and working correctly on our machine, let's run our first Python program with a simple Gui window. In sticking with programming tradition, let's say hello to TKinter. If you navigate to the exercise files, and go into the Chapter one directory, you'll find a file called Hello underscore TKinter. I'm going to right-click on that file and choose to open it with Idle. Here you can see that it's a simple program with just four lines of code.
I'll briefly describe what each line does but don't worry about understanding the specifics for now, we'll cover each of those in plenty of detail later. The first line imports all of the functions and variables from the TKinter package. Notice that TKinter is spelled out using all lowercase letters. I'm mentioning this, because it's one of the minor differences you'll need to consider if you're using Python 2. In Python 2, TKinter is spelled with a capital T, whereas in Python 3, it's written using all lowercase.
These exercise files are written for Python 3, so, you'll need to modify things accordingly if you're using Python 2. The second line down caused a TK constructor method to create a new top level widget, the main window, and assign it to the variable named Root. After that, we create a label with the text hello TKinter as a child of the root window, and we'll use the pack geometry management method to put it on the window. Finally, we run the main loop method for the root window. You can run this window in Idle by going to the run menu and selecting run module.
You should see a small window appear with the text hello TKinter. You can drag this window around the screen, and you can also grab the edge of it to re-size it to make it larger or smaller. When you're done, you can click the X to close it out. Just like that, with only four lines of code, we've run our first program to say hello to TKinter.
- Installing Python 3 and Tcl/Tk for Mac or Windows
- Creating and configuring themed Tk widgets
- Decorating the GUI with text labels and images
- Capturing input from buttons, menus, and entry fields
- Presenting choices with check boxes and radio buttons
- Using geometry managers to lay out the GUI
- Organizing widgets inside of frames and windows
- Handling user actions with event-driven programming
- Creating a simple drawing tool with the Canvas
- Prompting users with pop-up dialog boxes