User Interaction
Reacting to interface events
Python Events
An “event” in Python is when something
happens that our app can react to.
Event Types
The most common types of events are:
Mouse Events
click, move, hover
Keyboard Events
key down, key up
Change Events
resize, select, focus
Things We Need
To react to an event we need three things:
- A Widget
Which widget will trigger the event?
- The Event Name
Which event are we expecting?
- A Function
What code do we want to run in response?
Event Binding
We use the bind
function to link all the parts together:
import tkinter
window = tkinter.Tk()
def say_hello(event):
print("Why hello there!")
mystery_button = tkinter.Button(window)
mystery_button.config(text="Click Me")
mystery_button.bind("<Button>", say_hello)
mystery_button.grid()
window.mainloop()
This is just an example - we’ll do a demo next!
Events Demo
Open up eventsdemo.py
so we can add some event handling to it.
Click Events
Add a click event binding to the hello_button
:
hello_button = tkinter.Button(window)
hello_button.config(text="Click Me")
hello_button.bind("<Button>", say_hello)
hello_button.grid()
Clicking the button should print “Hello!” in the console.
More Click Events
Make the other buttons work, too:
- Add Random Fruit
- Delete Fruit
- Generate Recipe
Keyboard Events
Bind the name entry box to the <Return>
event,
so that pressing “enter” does the same as clicking the button.
Challenge: Stuff To Do
Complete todo.py
with events and functionality
so that it is a working To-Do app.
User Interaction: Complete!
Groovy, but what about more complex data…
Take me to the next chapter!