Python turtle and tkinter
Click Counter
Build a real window with a button and a counter, and see how fast you can click.
So far the turtle has drawn pictures. Today you will make an app with a window, a big number and a button. Every click adds one, and the number turns green when you reach 10. The windows, labels and buttons come from tkinter, which is built into Python.
You will learn
- Open a window with tkinter
- Show text with a Label and add a Button
- Run a function when a button is clicked
- Change what a label says while the program runs
You will need
- A computer with Thonny or IDLE, or this page's Run it here button
- Day 3's project, for functions
Words to know
- tkinter
- Python's built in toolkit for windows, labels, buttons and boxes to type in.
- widget
- A part of a window: a label, a button or a box to type in.
- event
- Something that happens while the program runs, such as a click.
- global
- Lets a function change a variable made outside it.
Step by step
Step 1: An empty window
Save a new file as
counter.pyand type this.tk.Tk()makes a window,titleandgeometryset its title and its size in pixels, 300 wide and 250 high, andmainloop()keeps it open, waiting for clicks.1import tkinter as tk2 3window = tk.Tk()4window.title("Click Counter")5window.geometry("300x250")6 7window.mainloop()An empty window called Click Counter. Watch out Call your filecounter.py, nevertkinter.py.Step 2: Show a number
A Label shows text in the window.
font=("Arial", 48, "bold")makes it big. Nothing appears until youpack()it, which places it in the window, under anything packed before it.New: lines 7 to 9.
1import tkinter as tk2 3window = tk.Tk()4window.title("Click Counter")5window.geometry("300x250")6 7label = tk.Label(window, text="0", font=("Arial", 48, "bold"))8label.pack()9 10window.mainloop()0A big 0 at the top of the window. Step 3: Add a button
A Button works the same way. Run it and click the button: nothing happens yet, because it has no job to do.
New: lines 10 to 12.
1import tkinter as tk2 3window = tk.Tk()4window.title("Click Counter")5window.geometry("300x250")6 7label = tk.Label(window, text="0", font=("Arial", 48, "bold"))8label.pack()9 10button = tk.Button(window, text="Click me!", font=("Arial", 14))11button.pack(pady=5)12 13window.mainloop()0Click me!A button under the number. Clicking it does nothing yet. Tippady=5adds 5 pixels of space above and below the button.Step 4: Make it count
The function
add_oneadds 1 tocountand puts the new number on the label.label.config(text=...)changes what a label says, andstrturns the number into text.command=add_onetells the button to call the function when it is clicked: no brackets afteradd_one, because the button calls it later, not now.global countlets the function change thecountmade outside it.New: lines 2 to 8 and 17.
1import tkinter as tk2 3count = 04 5def add_one():6 global count7 count = count + 18 label.config(text=str(count))9 10window = tk.Tk()11window.title("Click Counter")12window.geometry("300x250")13 14label = tk.Label(window, text="0", font=("Arial", 48, "bold"))15label.pack()16 17button = tk.Button(window, text="Click me!", font=("Arial", 14), command=add_one)18button.pack(pady=5)19 20window.mainloop()3Click me!After three clicks, the label says 3. Watch out Writecommand=add_one, notcommand=add_one(). With brackets, the function runs once when the window opens, and never again.Step 5: Add a title
Things appear in the order you pack them, so to put a title at the top, make and pack it before the number.
New: lines 14 to 16.
1import tkinter as tk2 3count = 04 5def add_one():6 global count7 count = count + 18 label.config(text=str(count))9 10window = tk.Tk()11window.title("Click Counter")12window.geometry("300x250")13 14title = tk.Label(window, text="How fast can you click?", font=("Arial", 14))15title.pack(pady=10)16 17label = tk.Label(window, text="0", font=("Arial", 48, "bold"))18label.pack()19 20button = tk.Button(window, text="Click me!", font=("Arial", 14), command=add_one)21button.pack(pady=5)22 23window.mainloop()How fast can you click?3Click me!A title over the counter. Step 6: Start again
A second button resets the count. Its function sets
countback to 0, and the label back to "0".New: lines 9 to 13 and 28 to 30.
1import tkinter as tk2 3count = 04 5def add_one():6 global count7 count = count + 18 label.config(text=str(count))9 10def reset():11 global count12 count = 013 label.config(text="0")14 15window = tk.Tk()16window.title("Click Counter")17window.geometry("300x250")18 19title = tk.Label(window, text="How fast can you click?", font=("Arial", 14))20title.pack(pady=10)21 22label = tk.Label(window, text="0", font=("Arial", 48, "bold"))23label.pack()24 25button = tk.Button(window, text="Click me!", font=("Arial", 14), command=add_one)26button.pack(pady=5)27 28reset_button = tk.Button(window, text="Reset", command=reset)29reset_button.pack()30 31window.mainloop()How fast can you click?5Click me!ResetA Reset button under Click me! Step 7: Turn green at 10
if count >= 10means if the count is 10 or more. Thenfg="green"turns the number's text green.fgstands for foreground, the colour of the text. Reset must turn it black again.New: lines 9, 10 and 15.
1import tkinter as tk2 3count = 04 5def add_one():6 global count7 count = count + 18 label.config(text=str(count))9 if count >= 10:10 label.config(fg="green")11 12def reset():13 global count14 count = 015 label.config(text="0", fg="black")16 17window = tk.Tk()18window.title("Click Counter")19window.geometry("300x250")20 21title = tk.Label(window, text="How fast can you click?", font=("Arial", 14))22title.pack(pady=10)23 24label = tk.Label(window, text="0", font=("Arial", 48, "bold"))25label.pack()26 27button = tk.Button(window, text="Click me!", font=("Arial", 14), command=add_one)28button.pack(pady=5)29 30reset_button = tk.Button(window, text="Reset", command=reset)31reset_button.pack()32 33window.mainloop()How fast can you click?12Click me!ResetAfter 12 clicks the number is green.
Test it
Tick each one when it works. If one does not, look back at the step it comes from.
Stretch challenges
Finished early? Try these. Each one has a hint if you get stuck.
Count down
Add a third button that takes 1 away.
Show a hint
Copy
add_oneand call the copytake_one. Changecount + 1tocount - 1, and make a button withcommand=take_one.Super clicker
Add a +10 button for when you are in a hurry.
Show a hint
One more function, one more button. The function adds 10 instead of 1.
Ten second challenge
Count down from 10 seconds, then switch off the Click me! button so the score cannot change.
Show a hint
window.after(1000, tick)calls the functiontickin 1000 milliseconds, one second. Insidetick, take 1 off the time and callwindow.after(1000, tick)again, until the time is up. Thenbutton.config(state="disabled")switches the button off.Show one answer
1import tkinter as tk2 3count = 04 5def add_one():6 global count7 count = count + 18 label.config(text=str(count))9 10time_left = 1011 12def tick():13 global time_left14 time_left = time_left - 115 timer.config(text=str(time_left) + " seconds left")16 if time_left > 0:17 window.after(1000, tick)18 else:19 button.config(state="disabled")20 21window = tk.Tk()22window.title("Click Counter")23window.geometry("300x250")24 25timer = tk.Label(window, text="10 seconds left", font=("Arial", 14))26timer.pack(pady=10)27 28label = tk.Label(window, text="0", font=("Arial", 48, "bold"))29label.pack()30 31button = tk.Button(window, text="Click me!", font=("Arial", 14), command=add_one)32button.pack(pady=5)33 34window.after(1000, tick)35window.mainloop()
The finished code
Show the whole program
1import tkinter as tk2 3count = 04 5def add_one():6 global count7 count = count + 18 label.config(text=str(count))9 if count >= 10:10 label.config(fg="green")11 12def reset():13 global count14 count = 015 label.config(text="0", fg="black")16 17window = tk.Tk()18window.title("Click Counter")19window.geometry("300x250")20 21title = tk.Label(window, text="How fast can you click?", font=("Arial", 14))22title.pack(pady=10)23 24label = tk.Label(window, text="0", font=("Arial", 48, "bold"))25label.pack()26 27button = tk.Button(window, text="Click me!", font=("Arial", 14), command=add_one)28button.pack(pady=5)29 30reset_button = tk.Button(window, text="Reset", command=reset)31reset_button.pack()32 33window.mainloop()Notes for the teacher
Timing
- 10 minutes: steps 1 to 3. The window appears quickly, which students enjoy.
- 20 minutes: step 4 is the big idea, a button calling a function. Draw it on the board: click, then
add_oneruns, then the label changes. - 15 minutes: steps 5 to 7 and the tests.
Mistakes to look out for
command=add_one()with brackets: the count goes to 1 as the window opens and the button then does nothing.- No
global countin the function: an UnboundLocalError aboutcount, the first time the button is clicked. label.config(text=count)withoutstr()works in tkinter, butlabel.config(text="Score: " + count)crashes with TypeError: can only concatenate str (not "int") to str.- Forgetting
pack(): the widget is made but never appears. - Code after
window.mainloop()does not run until the window is closed.
Going further
This is event driven programming: the program sets things up, then waits for events (clicks) and runs a function for each one. Compare it with the turtle programs, which ran from top to bottom and stopped.