我程序的这一部分允许用户从1到5中选择数字,并提供所选数字的总和。当总和达到30时我想禁用单选按钮。我该怎么做?
total_choices = [("1"),
("2"),
("3"),
("4"),
("5")]
var = tk.IntVar()
var.set(0)
sum = 0
def Calculator():
global sum
num = var.get()
sum = sum + num
if sum>30
# Grey out all the radio buttons
for val, choice in enumerate(total_choices):
tk.Radiobutton(root,
text=choice,
indicatoron = 0,
width = 10,
variable=var,
command=Calculator,
value=val).place(x=val*100,y=180)
答案 0 :(得分:0)
我会将所有单选按钮存储在列表中,然后在达到30时禁用每个按钮,如下所示:
total_choices = [("1"),
("2"),
("3"),
("4"),
("5")]
var = tk.IntVar()
var.set(0)
sum = 0
def Calculator():
global sum
global buttons
num = var.get()
sum = sum + num
if sum>30
# Grey out all the radio buttons
for b in buttons:
b.config(state=disabled)
global buttons
buttons = list()
for val, choice in enumerate(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))
答案 1 :(得分:0)
您可以通过从父母的子项列表中查找单选按钮来禁用单选按钮:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def disable_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 in range(1, 6):
tk.Radiobutton(root, text=i, variable=var, value=i,
command=disable_multiple_radiobuttons).pack()
tk.mainloop()
或者你可以把它们放在一个集合类型中,然后简单地禁用它们:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def on_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 in range(1, 6):
radiobuttons[i] = tk.Radiobutton(root, text=i, variable=var,
value=i, command=on_rb_press)
radiobuttons[i].pack()
tk.mainloop()