Skip to content Skip to sidebar Skip to footer

How To Disable Multiple Radiobuttons In Python?

This part of my program allows user to choose numbers from 1 to 5 and provide the sum of all numbers chosen. I want to disable the radio buttons when the sum reaches 30. How can I

Solution 1:

You can disable radio buttons by looking them up from the children list of their parents:

try:                        # In order to be able to import tkinter forimport tkinter as tk    # either in python 2 or in python 3except ImportError:
    import Tkinter as tk


defdisable_multiple_radiobuttons():
    global total
    print(repr(sum_label['text']))
    total += var.get()
    sum_label['text'] = total
    if total >= 30:
        for child in root.winfo_children():
            if child.winfo_class() == 'Radiobutton':
                child['state'] = 'disabled'


root = tk.Tk()
var = tk.IntVar(value=1)
total = 0
sum_label = tk.Label(root, text=total)
sum_label.pack()
for i inrange(1, 6):
    tk.Radiobutton(root, text=i, variable=var, value=i,
        command=disable_multiple_radiobuttons).pack()
tk.mainloop()

or you can put them in a collection type and simply disable them at ease:

try:                        # In order to be able to import tkinter forimport tkinter as tk    # either in python 2 or in python 3except ImportError:
    import Tkinter as tk


defon_rb_press():
    sum_label['text'] += var.get()
    if sum_label['text'] >= 30:
        for key in radiobuttons:
            radiobuttons[key]['state'] = 'disabled'


root = tk.Tk()
sum_label = tk.Label(root, text=0)
sum_label.pack()
radiobuttons = dict()
var = tk.IntVar(value=1)
for i inrange(1, 6):
    radiobuttons[i] = tk.Radiobutton(root, text=i, variable=var,
                                                value=i, command=on_rb_press)
    radiobuttons[i].pack()
tk.mainloop()

Solution 2:

I would store all the radio buttons in a list, then disable every buttons when you reach 30, as seen below :

total_choices = [("1"),
                 ("2"),
                 ("3"),
                 ("4"),
                 ("5")]
var = tk.IntVar()
var.set(0)  

sum = 0defCalculator():
    globalsumglobal buttons
    num = var.get()
    sum = sum + num
    ifsum>30# Grey out all the radio buttonsfor b in buttons:
            b.config(state=disabled)

global buttons
buttons = list()
for val, choice inenumerate(total_choices):
    buttons.append(tk.Radiobutton(root,
        text=choice,
        indicatoron = 0,
        width = 10,
        variable=var,
        command=Calculator,
        value=val))
    buttons[-1].place(x=val*100,y=180))

Post a Comment for "How To Disable Multiple Radiobuttons In Python?"