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 带标签的分隔符
基础教程推荐
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
