python - 制表不同复选框中的复选框 - 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')
正如您在图像中看到的那样,复选框的列表很好,并且不知道为什么会发生这种情况,因为标签的长度都相同。
我也尝试过使用网格而不是包,但仍然无法正常工作。 使用网格
解决方案
您可以设置检查按钮的宽度(以字符为单位),而不是用空格填充检查按钮的文本(这不起作用,因为所有字符的长度都不相同):
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()
这使:
推荐阅读
- python - 表单输入(数组)作为 Python 中的 PUT 请求
- c++ - C++ 使用移动语义将参数传递给另一个函数
- c# - ACE OLEDB 连接到 Access Runtime 2016
- c# - ControlPaint.DrawBorder() 仅绘制顶部和左侧
- angular - 在 Angular 应用程序中使用 Jest 测试 Redux Store 时出现错误“操作必须是普通对象”
- c# - 从另一个 ASP.NET Core 类调用 HTTPPost 路由控制器
- html - 使用 CSS 弹出图像时表格单元格大小发生变化
- c# - 使用rejectUnauthorized: true 节点不接受从pems生成的pfx证书并使用c# httpClient作为客户端
- java - 使用 AzureFunctions 删除 cosmosDB 项
- python - Keras LSTM 模型不学习