首页 > 解决方案 > 制表不同复选框中的复选框 - Tkinter

问题描述

我正在用 Tkinter 做一个 GUI,我试图显示两个复选框中的复选框。我尝试(如您在代码中看到的那样)检查问题是否是标签长度不同,但在需要时添加了一些空格之后;看来这不是问题。任何想法为什么会发生这种情况?

class Checkbar(Frame):
    def __init__(self, parent=None, picks={}, side=LEFT, anchor=W, list_keys=[]):
        Frame.__init__(self, parent)
        self.vars = []

        for key, value in picks.items():
            var = IntVar()
            chk = Checkbutton(self, text=self.SameLength(list_keys, key), variable=var)
            button_ttp = ToolTip(chk, value)
            chk.pack(side=side, anchor=anchor, expand=YES, )

    def SameLength(self, listStrings, word):
        return word.ljust(len(max(listStrings, key=len)), '0')

图片

正如您在图像中看到的那样,复选框的列表很好,并且不知道为什么会发生这种情况,因为标签的长度都相同。

我也尝试过使用网格而不是包,但仍然无法正常工作。 使用网格

标签: pythoncheckboxtkinterlabel

解决方案


您可以设置检查按钮的宽度(以字符为单位),而不是用空格填充检查按钮的文本(这不起作用,因为所有字符的长度都不相同):

Checkbutton(.., width=maxwidth, anchor='w', ...)

哪里maxwidth = len(max(list_keys, key=len))。您还需要将anchor选项设置'w'为将复选框向左对齐。

这是我用来测试答案的完整代码:

from tkinter import *

class Checkbar(Frame):
    def __init__(self, parent=None, picks={}, side=LEFT, anchor=W, list_keys=[]):
        Frame.__init__(self, parent)
        self.vars = []
        maxwidth = len(max(list_keys, key=len))

        for key, value in picks.items():
            var = IntVar()
            chk = Checkbutton(self, text=key, variable=var, width=maxwidth, anchor='w')
            # button_ttp = ToolTip(chk, value)
            chk.pack(side=side, anchor=anchor, expand=YES, )



root = Tk()
list_keys = ['1', '2', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight']

Label(root, text='Select keyword(s):').grid(row=0, column=0)
Checkbar(root, picks={k: k for k in list_keys[:4]}, list_keys=list_keys).grid(row=0, column=1, sticky='w')
Checkbar(root, picks={k: k for k in list_keys[4:]}, list_keys=list_keys).grid(row=1, column=1, sticky='w')
root.mainloop()

这使:

截屏


推荐阅读