Python Tkinter TTK Separator With Label(Python Tkinter TTK 带标签的分隔符)
问题描述
我正在尝试创建一个在标签后面包含分隔符的自定义小部件.我希望分隔符在标签后面延伸到窗口的每一侧(使用网格).我尝试自己创建这个,但我无法让分隔符粘在边缘.
I am trying to create a custom widget that includes a separator behind a label. I would like the separator to stretch out behind the label to each side of the window (using grid). I tried to create this myself, but I couldn't get the separator to stick to the edges.
import tkinter as tk
from tkinter import ttk
class LabelSeparator (tk.Frame):
def __init__ (self, parent, text = "", width = "", *args):
tk.Frame.__init__ (self, parent, *args)
self.separator = ttk.Separator (self, orient = tk.HORIZONTAL)
self.separator.grid (row = 0, column = 0, sticky = "ew")
self.label = ttk.Label (self, text = text)
self.label.grid (row = 0, column = 0, padx = width)
if __name__ == "__main__":
root = tk.Tk ()
root.geometry ("200x40")
label = LabelSeparator (root, text = "Label", width = 15)
label.grid (sticky = "ew")
label2 = LabelSeparator (root, text = "A Second Label", width = 15)
label2.grid (sticky = "ew")
root.mainloop ()
我发现扩展分隔符的唯一方法是增加标签上的 padx,但这并不能真正解决问题.
The only way I found to expand the separator was to increase the padx on the label, but that doesn't really fix the problem.
我应该提到我对创建自定义小部件非常陌生.
I should mention that I'm very new to creating custom widgets.
推荐答案
你的代码唯一的问题是你没有调用 grid_columnconfigure
来告诉 tkinter 如何处理额外的空间.由于您没有告诉内部框架如何处理多余的空间,因此它将其留空.当小部件放置在其父级中并展开时,您的内部小部件没有使用额外的空间.
The only problem with your code is that you haven't called grid_columnconfigure
to tell tkinter what to do with extra space. Since you didn't tell the inner frame what to do with extra space, it left it blank. When the widget is placed in its parent and expands, your inner widgets weren't using the extra space.
在您的 __init__
中添加以下内容:
Add the following in your __init__
:
self.grid_columnconfigure(0, weight=1)
作为一般经验法则,您总是希望在使用网格来管理其子级的父级中设置至少一行和一列的权重.
As a general rule of thumb, you always want to set the weight of at least one row and one column in a parent that uses grid to manage it's children.
这篇关于Python Tkinter TTK 带标签的分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python Tkinter TTK 带标签的分隔符


- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 沿轴计算直方图 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- padding='same' 转换为 PyTorch padding=# 2022-01-01