Tkinter – part 2 – Binding

Binding the root

In this second part, after creating a window and adding a frame and a label in the first part, we will see how to bind an element (or the window itself) to an event made by the user. In the first example we’ll code how to interact with a click of the mouse.

In [5]:
import tkinter as tk

def clicked(event):
    print("You binded the root with Button-1")
    print("Remember to write <Button-1>")

root = tk.Tk()
root.geometry("400x400+100+100")
root.bind("<Button-1>", clicked)
root.mainloop()

In this code we programmed an event linked to the click of the mouse on the window. Whent this event occurs the clicked function will start, printing some text on the console.

Tkinter to make a window – video 1

A simple example

In this example we change the color of the window when we click on it.

import tkinter as tk
import random

def clicked(event):
    root['bg'] = random.choice(['red','yellow','blue','orange','green','white'])
    root.title(root['bg'])

root = tk.Tk()
root.title("Click to change color")
root.geometry("400x400+100+100")
root.bind("<Button-1>", clicked)
root.mainloop()
tkinter pyhton
tkinter pyhton

Tkinter test for students

Tkinter articles

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.