Examples with tkinter (binding to the mouse click event)

A simple example of how to interact with a window clicking the mouse button. We will build a window and bind to the root the event press the mouse button to make the window change color.

#!/usr/bin/python
from random import choice
import tkinter
root = tkinter.Tk()
root.title("root")
root.geometry("400x400+200+200")
# Code to add widgets will go here...

sceltavecchia = ""
colori = ['red','yellow','green','azure',"blue","coral","gold"]
def changecolor(event):
	global colori, sceltavecchia
	if sceltavecchia != "":
		colori.pop(colori.index(sceltavecchia))
		scelta = choice(colori)
		colori.append(sceltavecchia)
	else:
		scelta = choice(colori)
	root['bg'] = scelta
	sceltavecchia = scelta

label = tkinter.Label(root, text="Click where you want to change color")
label.pack(fill=tkinter.BOTH)

root.bind("", changecolor)
root.mainloop()

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.