Python Tkinter TTK 带标签的分隔符

2022-01-25 00:00:00 python tkinter label separator

问题描述

我正在尝试创建一个在标签后面包含分隔符的自定义小部件.我希望分隔符在标签后面延伸到窗口的每一侧(使用网格).我尝试自己创建这个,但我无法让分隔符粘在边缘.

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.

相关文章