Home > Blockchain >  tkinter radiobutton event when variable change
tkinter radiobutton event when variable change

Time:02-16

I am a beginner in tkinter, and I reach a trouble. I would like to have a radio button group which enable or disable some buttons, scales, ..., in function of which radio button is selected. Those button group are connected to a variable. To disable/enable widgets, I use button group command. Everything works when I click on radio buttons. But if the variable changed, the radio button changed without calling the radio command, so other widgets are not updated.

Here is a very simple code of what I want to do

from tkinter import ttk
import tkinter as tk

root = tk.Tk()

frame = ttk.LabelFrame(root, text='choice your futur')
frame.pack(fill="both", expand="yes", padx=5, pady=5)

selection = tk.IntVar()

def onButtonClic():
    selection.set(1)

bt = tk.Button(frame, text='continue', command=onButtonClic)
bt.grid(column=0, row=1, columnspan=2, sticky='ew')


def onRadioButtonChange():
    if selection.get() != 0:
        bt.configure(state = tk.DISABLED)
    else:
        bt.configure(state = tk.NORMAL)

tk.Radiobutton(frame, command=onRadioButtonChange, text = "blue pill", variable = selection, value = 0).grid(column=0, row=0, sticky='nw')
tk.Radiobutton(frame, command=onRadioButtonChange, text = "red pill", variable = selection, value = 1).grid(column=1, row=0, sticky='nw')

root.mainloop()

If I select the red pill, button is disabled. When blue pill is selected, and click on button (which set radio variable to 1: the red pill value), the red pill is selected, but button is still enable. I would like when the variable changed, then the radio command be called.

Best regards JM

CodePudding user response:

You can use tkinter variable .trace_add() function instead:

...

def onRadioButtonChange(*args):
    if selection.get() != 0:
        bt.configure(state = tk.DISABLED)
    else:
        bt.configure(state = tk.NORMAL)

# call onRadioButtonChange() when the variable is updated
selection.trace_add('write', onRadioButtonChange)

tk.Radiobutton(frame, text = "blue pill", variable = selection, value = 0).grid(column=0, row=0, sticky='nw')
tk.Radiobutton(frame, text = "red pill", variable = selection, value = 1).grid(column=1, row=0, sticky='nw')

...
  • Related