一个简单的解决方案是使用变量来跟踪
Radiobutton
最后按下(我称之为
prev_btn
这里)。
这个
command
函数可以检查此值,并且只有当它与上次调用函数时相比发生更改时才能执行。之后,该函数存储更新的按钮值。
import tkinter as tk
def on_choice():
# set prev_btn as a global so this function can modify its value
global prev_btn
# only trigger the useful stuff if the button is different from last time
if radiobutton_variable.get() != prev_btn: # if button changed...
print('Function executed')
# store the value of the most recently pressed button
prev_btn = radiobutton_variable.get()
root = tk.Tk()
root.geometry('300x150')
radiobutton_variable = tk.StringVar()
radiobutton_variable.set(1)
# define a variable to store the current button state
# (you could also set this to '1', but doing it this way means you won't have to
# update the default value in two places in case you decide to change it above!)
prev_btn = radiobutton_variable.get()
button_1 = tk.Radiobutton(root, text='Button 1', variable=radiobutton_variable, value=1, command=on_choice)
button_2 = tk.Radiobutton(root, text='Button 2', variable=radiobutton_variable, value=2, command=on_choice)
button_1.pack()
button_2.pack()
root.mainloop()