Python Tkinter TTK 带标签的分隔符 [英] Python Tkinter TTK Separator With Label

查看:136
本文介绍了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 带标签的分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆