Tkinter mouse binding basic usage
The basic application of mouse events, this program will create a 300 x 180 size window when executed, and when the left mouse button is clicked, the coordinates of the click event will be listed in the Python Shell window.
Tkinter mouse binding basic usage Example#1
from tkinter import *
def callback(event): # Event Handler
print("Clicked at",event.x,event.y) # Print Coordinate
root = Tk()
root.title("apidemos.com")
frame = Frame(root,width=300,height=180,bg="yellow")
frame.bind("<Button-1>",callback) # Binding callback
frame.pack()
root.mainloop()
Output:
Here is the Python Shell demonstration output screen.
In the event handler bound in line 3 of the program must pay attention to the callback(event) need to have parameters event, event name can be customized, this is because the event will pass the event object to this event handler.
Tkinter mouse binding basic usage Example#2
When moving the mouse, you can see the current coordinates of the mouse at the bottom right of the window.
from tkinter import *
def mouseMotion(event): # Mouse Move
x = event.x
y = event.y
textvar = "Current mouse position -> x:{}, y:{}".format(x,y)
var.set(textvar)
root = Tk()
root.title("apidemos.com")
root.geometry("300x180")
x, y = "###", "###"
var = StringVar()
text = "Current mouse position -> x:{}, y:{}".format(x,y)
var.set(text)
lab = Label(root,textvariable=var,bg="yellow") # Create a label
lab.pack(anchor=S,side=RIGHT,padx=10,pady=10) # lab.pack(anchor=S,side=RIGHT,padx=10,pady=10)
# root.bind("<Motion>",mouseMotion)
root.bind("<Button-1>",mouseMotion) # Adding an Event Handler # "<Motion>"
root.bind("<Button-3>",mouseMotion)
# "<B1-Motion>"
root.mainloop()
Output:
Tkinter mouse binding basic usage Example#3
When this program is executed, if the mouse cursor enters the Exit function button, it will show "Mouse enters the Exit function button" in the yellow bottom label area, if the mouse cursor leaves the Exit function button, it will show "Mouse leaves the Exit function button" in the yellow bottom label area, if you click the Exit button, the program ends.
from tkinter import *
def enter(event): # Enter Event Handler
x.set("Mouse into Exit function button")
def leave(event): # Leave Event Handler
x.set("Mouse out of Exit function button")
def myExit(event):
print("Program exit cxq")
root.destroy()
root = Tk()
root.title("apidemos.com")
root.geometry("900x540")
# btn = Button(root,text="Exit",command=root.destroy)
btn = Button(root,text="Exit")
btn.bind("<Button-1>",myExit)
btn.pack(pady=30)
btn.bind("<Enter>",enter) # Go to the binding enter
btn.bind("<Leave>",leave) # Leave the binding leave
x = StringVar()
x.set("Initial state...")
lab = Label(root,textvariable=x,
bg="yellow",fg="blue",
height=4,width=50,
font="Times 12 bold")
lab.pack(pady=30)
root.mainloop()
Output: