I want to make a Tkinter button respond to a left and right mouse click differently. How can I do this?
Binding the mouse button to a particular function will do it ...
from Tkinter import * def left(event): root.title('clicked left') btn1.config(fg='blue') def right(event): root.title('clicked right') btn1.config(fg='red') root = Tk() root.title('click left or right on button') btn1 = Button(root, text=' Click on me ... ', width=40) btn1.pack() btn1.bind('<Button-1>', left) # bind left mouse click btn1.bind('<Button-3>', right) # bind right mouse click root.mainloop()
I noticed the argument 'event'. What does it contain? What can it be used for? Right now it seems to be just a dummy argument that is not used for anything.
The argument 'event' is the event that called your function. In your case it would be a mouse-click. You could retrieve the mouse pointer position coordinates from the event ...
import Tkinter as tk def click(event): """display the click coordinates""" str1 = 'x=', event.x, 'y=', event.y root.title(str1) root = tk.Tk() root.title('click left or right on button') btn1 = tk.Button(root, text=' Click on me ... ', width=40) btn1.pack() btn1.bind('<Button-1>', click) # bind left mouse click root.mainloop()
Also notice that with the DrPython IDE the moment you type 'tk.' the code completion assistant kicks in, a nice feature.