[英]Python tkinter. Selected checkbuttons to list
我遇到了一個問題,谷歌沒有給我答案,所以我在這里。 我的程序有一個列表並將其轉換為檢查按鈕。 現在我想讓選定的項目與他們一起工作。 這是代碼:
import tkinter
from tkinter import *
mylist = ['Alfa', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Golf', \
'Hotel', 'India', 'Juliett', 'Kilo', 'Lima']
class CheckButton:
def __init__(self, master, title):
self.var = IntVar()
self.var.set(0)
self.title = title
self.cb = Checkbutton(master, text=title, variable=self.var, onvalue=1, \
offvalue=0)
self.cb.pack(side = TOP)
def select():
chosen = []
for i in checks:
#if ??? <--- Here is my issue
# chosen.append(checks[i])
#Window
window = Tk()
f1 = Frame(window)
checks = []
for i in mylist:
checks.append(CheckButton(window, i))
button = Button(window, text="Select!", command=select)
button.pack(side="bottom")
window.mainloop()
我嘗試使用 get(i)、checks.state(i) 和其他一些,但它不起作用。 那么我應該怎么做才能獲得所選選項的列表?
請注意, CheckButton
的實例不是 checkbutton 小部件,因此您不能在其上使用.get()
。
對於您的情況,您需要使用i.var.get()
來獲取相應復選框的 state :
def select():
chosen = []
for i in checks:
if i.var.get():
chosen.append(i.title)
print(chosen)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.