In my Tkinter app, I want to execute on_choice
function when selecting Radiobutton
by using command=on_choice
. When pressing on a radiobutton when it's already selected, the function should not be executed again. It should only be executed once after switching from another radiobutton, so the user could not repeatedly execute a function by pressing on the same radiobutton. Is there a way to prevent an execution of a command when Radiobutton
is already selected?
The code:
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()
A simple solution is to use a variable to track which Radiobutton
was pressed last (I've called it prev_btn
here).
The command
function can inspect this value and only execute if it's changed from the last time the function was called. After that, the function stores the updated button value.
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()