嘗試從 checkbutton 列表中獲取選定的值,而不必創建 10 個或更多 checkbutton 和 var。
我得到這個來測試這個想法
from tkinter import Tk, StringVar, Checkbutton, Button, BooleanVar
root = Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry("%dx%d+0+0" % (w, h))
def def1():
print("1")
def def2():
print("2")
def def3():
print("3")
def def4():
print("4")
def def5():
print("5")
def def6():
print("6")
def letssee():
print(addlist)
nomtestes = ["def1", "def2", "def3", "def4", "def5", "def6"]
clltes = 0
rwwtes = 0
addlist=[]
username_cbs = dict()
for name in nomtestes:
if clltes == 5:
rwwtes += 1
clltes = 0
username_cbs[name] = Checkbutton(root, text=name, onvalue=True, offvalue=False)
username_cbs[name].var = BooleanVar()
username_cbs[name]['variable'] = username_cbs[name].var
username_cbs[name]['command'] = lambda w=username_cbs[name]: upon_select(w)
username_cbs[name].grid(row=rwwtes, column=clltes, pady=2)
clltes += 1
Button(root, text="OK",command=letssee).grid(column=0, row=5, padx=1, pady=15)
def upon_select(widget):
if widget.var.get() == True:
addlist.append(widget['text'])
else:
addlist.remove(widget['text'])
root.mainloop()
在這個例子中,我試圖打印我選擇的所有復選按鈕,但是,要運行添加到 addlist 的函數
任何想法如何做到這一點?
謝謝
您可以創建一個字典,將字符串值映射到相應的函數,然後將它們添加或刪除到列表中。
nomtestes = {"def1": def1, "def2": def2, "def3": def3, "def4": def4, "def5": def5, "def6": def6}
addlist = list()
from_input = ["def1", "def4"]
for i in from_input:
addlist.append(nomtestes[i])
for def_function in addlist:
def_function()
Out: 1
4
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句