pythontkinter,创建一个清单框,将选中的项目作为列表返回

2024-04-26 03:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用了这篇https://stackoverflow.com/a/50399359/10343540文章中提供的类,但是getCheckedItems()方法总是返回列表中的所有项,而不仅仅是选中的项。代码如下:

import tkinter as tk
class ChecklistBox(tk.Frame):
    def __init__(self, parent, choices, **kwargs):
        tk.Frame.__init__(self, parent, **kwargs)

        self.vars = []
        bg = self.cget("background")
        for choice in choices:
            var = tk.StringVar(value=choice)
            self.vars.append(var)
            cb = tk.Checkbutton(self, var=var, text=choice,
                                onvalue=choice, offvalue="",
                                anchor="w", width=20, background=bg,
                                relief="flat", highlightthickness=0
            )
            cb.pack(side="top", fill="x", anchor="w")


    def getCheckedItems(self):
        values = []
        for var in self.vars:
            value =  var.get()
            if value:
                values.append(value)
        return values

top = tk.Tk()
col_list = ['ROI', 'YoY', 'Other']
checklist = ChecklistBox(top, col_list, bd=1, relief="sunken", background="white")
checklist.pack()
def command() :
    print(checklist.getCheckedItems())

tk.Button(top, text="Choose Columns", command=command).pack()
top.mainloop()

Tags: selfvaluevartopdefvarscommandpack