Back to article
GUI Programming in Python For Beginners: Create a Timer in 30 Minutes
Saving Absent-Minded Geeks From Soggy Gardens and Burned Food
March 26, 2009
Python programming is all the rage, because the language has such simple, clean syntax, is easy to learn and has lots of libraries available. But best of all, you're not limited to writing command-line applications. Python has at least four ways to make graphical apps, but today I'll concentrate on one: TkInter.
TkInter isn't necessarily the most powerful of the Python windowing packages, but it's well supported on all operating systems. You can give your application to your Windows- and Mac-using friends and they'll be able to run it, as long as they have Python installed. On Linux, though, you may have to install it: on Ubuntu or Debian the package is named python-tk, while in Fedora it's tkinter.
For a project, start with a simple one. How about an "eggtimer"? I'm always forgetting that I have cornbread baking in the oven, or that I turned on the sprinklers in the garden. I need something to remind me.
Let's start with a very simple Tkinter program. Paste the following into your editor of choice (vim, emacs, kate, leafpad or whatever) and write it to a file named, say, eggtimer:
You can run your script by typing:
or, if you make the file executable (see the shell scripting article), you can run it just by typing
Okay, a single button isn't so useful. For a timer, you need to be able to set when it will alert you. And for that, a Scale is a good choice. It gives you a slider you can use to choose how many minutes you want your timer to wait. Add these two lines to your script right before the line where you create your button:
scale = Scale(root, from_=1, to=45, orient=HORIZONTAL, length=300)
Of course, Tkinter has other controls (called widgets) besides Scale.
You can make an Entry if you want to read in a text string (or type in the number of minutes), a Checkbutton or Radiobutton to set yes/no options or other binary options, or a Text widget to let the user enter a lot of text (more than one line).
You can also add controls to make things look nicer. For instance, you can add a Label just before you create the Scale, to specify that the slider means a time in minutes:
minutes = Label(root, text="Minutes:")
Figure 3 shows what the window looks like now, and Listing 3 has the code.