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.
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.
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()