Python Tkinter Tk支持核对表框?

时间:2018-05-17 18:52:22

标签: python python-3.x tkinter

我正在尝试在GUI中创建核对表框。可以做Tkinter吗?(我不想要复选框列表)

Reference image

我知道Python Wx GUI开发有这种支持,但我正在寻找Tk的支持。

如果有人有想法请分享链接了解详情或方法吗?

1 个答案:

答案 0 :(得分:4)

Tkinter没有像wxPython的ChecklistBox这样的小部件。但是,在框架内创建一组检查按钮是很容易的。

示例:

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

使用示例:

choices = ("Author", "John", "Mohan", "James", "Ankur", "Robert")
checklist = ChecklistBox(root, choices, bd=1, relief="sunken", background="white")
...
print("choices:", checklist.getCheckedItems())

enter image description here