在我的 Tkinter 应用程序中,我想在使用
on_choice
选择 Radiobutton
时执行 command=on_choice
函数。当按下已选择的单选按钮时,不应再次执行该功能。它只能在从另一个单选按钮切换后执行一次,因此用户不能通过按下同一个单选按钮来重复执行功能。有没有办法在已选择 Radiobutton
时阻止执行命令?
代码:
import tkinter as tk
def on_choice():
print('Function executed')
root = tk.Tk()
root.geometry('300x150')
radiobutton_variable = tk.StringVar()
radiobutton_variable.set(1)
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()
一个简单的解决方案是使用一个变量来跟踪最后按下的是哪个
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:
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()