首页 > 解决方案 > 将复选框存储到列表 tkinter

问题描述

我对 tkinter 相当陌生,能够获得以下代码。

from tkinter import *
from tkinter import filedialog
master = Tk()
v = IntVar()
v.set(1)
var1 = IntVar()
var2 = IntVar()
var3 = IntVar()
CategorySubmit= IntVar()
my_list = [{"Kitchen":var1},{"Electric Supply":var2},{"Books":var3}]
def get_boxes(value):
    #store the checked boxes for later use
    pass
def get_value(value):
    #print(value)
    if value=="Category":
        for widget in master.winfo_children():
            widget.destroy()
        row =1
        for i in my_list:
            Checkbutton(master, text=list(i.keys())[0], variable=list(i.values())[0]).pack()
            row+=1
        Button(master, text="Submit", variable=CategorySubmit,command=get_boxes).pack()
        #save the check boxes made by user into a list then quit master
    else:
        file_chosen =filedialog.askopenfilename(title='Please Select Input File', filetypes=[('Excel files', ('.xlsx', '.csv', '.xls', 'xlsm'))])
        print(f"Done: {file_chosen}")
        master.destroy()

MODES = [
("Choice 1","ID"),
("Choice 2","Category"),
("Choice 2","Full"),
]
choice_made= StringVar()
choice_made.set('Choice 1')
for text,mode in MODES:
    Radiobutton(master,text=text,variable=choice_made,value=mode).pack()
but = Button(master,text="Submit",command=lambda: get_value(choice_made.get()))
but.pack()

master.mainloop()
print(file_chosen) #gives undefined error ?

我需要将复选框中的值存储到列表中,以便以后使用。当对于外部的变量名时,我也有一个错误master.mainloop(),它给出了NameError: name 'file_chosen' is not defined

My idea is when "Choice 1" or "Choice 3" are picked a fileprompt is given so I can continue with my script later on, else if "Choice 2" 3 checkboxes that I store in a list

标签: pythontkinter

解决方案


file_chosen变量在函数内部是局部的get_value()。要扩展其范围,您必须声明为全局:

def get_value(value):
    global file_chosen

推荐阅读