python ttk separator,带标签的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 ()

0a4f1441e5ae78dfac10cc46083ea93c.png

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.

解决方案

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值