Tkinter button only sinks when pressed with a left click

Viewed 153

Tkinter beginner here

I've been working on a virtual mouse project and I stumbled upon a small problem when creating the GUI that corresponds to mouse functions. Specifically, I have a function I want to perform when a UI button is clicked and the button to sink when pressed, while the others stay raised. The callback function works with every mouse button as intended, but the issue is that the UI button will only sink when pressed with a left mouse click.

Is there a way to make the UI buttons sink regardless of which mouse button I press? For example, I want to make a UI button sink by using the middle mouse button.

Here is my code, Using python 3.8:

import tkinter as tk


root = tk.Tk()

switch_frame = tk.Frame(root)
switch_frame.pack()



root.geometry("230x200")

def hh(event,):
    print('This works as intended with all the mouse buttons, but the UI button only sinks when pressed with a left click')
   

switch_variable = tk.StringVar(value="off")

b1 = tk.Radiobutton(switch_frame, text='Left Click',width=15,height=6,variable=switch_variable,indicatoron=False,value="left_click")
b2 = tk.Radiobutton(switch_frame, text='Right Click',width=15,height=6,variable=switch_variable,indicatoron=False,value="right_click")
b3 = tk.Radiobutton(switch_frame, text='Double Click',width=15,height=6,variable=switch_variable,indicatoron=False,value="double_click")
b4 = tk.Radiobutton(switch_frame, text='Middle Click',width=15,height=6,variable=switch_variable,indicatoron=False,value='middle_click')

#Used binding "<Button>" to bind the function with all mouse buttons
b1.bind("<Button>", hh)
b2.bind("<Button>", hh)
b3.bind("<Button>", hh)
b4.bind("<Button>", hh)



b1.grid(column=0, row=0)   
b2.grid(column=1, row=0)   
b3.grid(column=0, row=1)   
b4.grid(column=1, row=1)  

root.call('wm', 'attributes', '.', '-topmost', '1')
root.mainloop()

Thanks for your help!

1 Answers

You could do it by "invoking" the Radiobutton widget that was clicked, which is one of the pieces of information contained in the event argument passed to your even-handler.

def hh(event,):
    print('This works as intended with *all* the mouse buttons.')
    event.widget.invoke()
Related