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

查看:329
本文介绍了带标签的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__中添加以下内容:

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天全站免登陆