[Python] Tkinter Radiobutton executes a command while already selected

Discussão em 'Python' iniciado por Stack, Dezembro 20, 2024.

  1. Stack

    Stack Membro Participativo

    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()

    Continue reading...

Compartilhe esta Página