使用此列表我希望能够获得两个输入。那将存储在变量中。有什么建议??请帮助我是tkinter的新手。
import tkinter as tk
class App():
def __init__(self, master):
self.master = master
self.type_integration = None
self.typeChoice = tk.StringVar()
self.typeChoice.set(None) # This fixes the grayness of the radio buttons!
self.typeFrame = tk.Frame(master)
OPTIONS = [('Arsenal','Arsenal'),('Aston Villa','Aston Villa'),('Burnley','Burnley'),('Chelsea','Chelsea'),('Crystal Palace','Crystal Palace'),('Everton','Everton'),('Hull','Hull'),('Leicester','Leicester',),('Liverpool','Liverpool'),('Manchester City','Manchester City'),('Manchester United','Manchester United'),('Newcastle United','Newcastle United'),('Queens Park Rangers','Queens Park Rangers'),('Southampton','Southampton'),('Stoke','Stoke'),('Sunderland','Sunderland'),('Swansea','Swansea'),('Tottenham','Tottenham'),('West Bromwich Albion','West Bromwich Albion'), ('West Ham','West Ham')]
for text, value in OPTIONS:
tk.Radiobutton(self.typeFrame, text=text, variable=self.typeChoice, value=value).pack(anchor = 'w')
tk.Button(self.typeFrame, text="Confirm Home Team", command=self.exit).pack(anchor = 'w')
self.typeFrame.pack()
def exit(self):
self.type_integration = self.typeChoice.get()
self.master.destroy()
def getinput(self):
return self.type_integration
master = tk.Tk()
app = App(master)
tk.mainloop()
home = app.getinput()
print(home)
我需要再上一堂课吗?或者我可以重用代码??非常感谢帮助。我愿意倾听任何事情,因为我不是很好。
答案 0 :(得分:3)
RadioButton
是一个Tkinter小部件,用于实现一个选项。
您需要使用CheckButton
widget来做您想做的事。
def __init__(self, master):
...
self.variables = variables = []
for text, value in OPTIONS:
var = tk.StringVar()
variables.append(var)
tk.Checkbutton(self.typeFrame, text=text, variable=var,
onvalue=text, offvalue='').pack(anchor = 'w')
...
def exit(self):
self.type_integration = ','.join(v.get() for v in self.variables if v.get())
self.master.destroy()
<强>更新强>
最多限制2个选择:
def __init__(self, master):
...
self.variables = []
self.checkboxs = []
for text, value in OPTIONS:
var = tk.StringVar()
cb = tk.Checkbutton(self.typeFrame, text=text, variable=var,
onvalue=text, offvalue='', command=self.limit2)
cb.pack(anchor = 'w')
self.variables.append(var)
self.checkboxs.append(cb)
...
def limit2(self):
if sum(bool(v.get()) for v in self.variables) >= 2:
# Disable non-selected items to limit selection
for cb, v in zip(self.checkboxs, self.variables):
if not v.get():
cb['state'] = 'disabled'
else:
for cb in self.checkboxs:
cb['state'] = 'normal'