User Interaction

Reacting to interface events

Python Events

An “event” in Python is when something
happens that our app can react to.

Widget Events

Tkinter Widgets trigger different types of events
when a user interacts with the app.

Event Types

The most common types of events are:

  • A Computer Mouse
    Mouse Events
    click, move, hover
  • Gaming Keys
    Keyboard Events
    key down, key up
  • Resizing A Window
    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.

Thumbs Up!

User Interaction: Complete!

Groovy, but what about more complex data…
Take me to the next chapter!

Loading...

Widget Events

Mouse Buttons

  • <Button>
    Mouse click, any button
  • <Button-1>
    Mouse left-click
  • <Button-2>
    Mouse middle-click
  • <Button-3>
    Mouse right-click
  • <Button-4>
    Mouse scroll-up
  • <Button-5>
    Mouse scroll-down

Mouse Movement

Mouse by Olivier Guin from the Noun Project

Gaming Keys by Daniel Sikorski from the Noun Project

Resize by Mister Pixel from the Noun Project