当使用Tkinter的包布局时,如何在调整窗口大小时使Label的强度等于窗口的宽度?

问题描述 投票:0回答:1

我正在使用packTkinter布局,我允许调整应用程序窗口的大小。

我无法弄清楚的是如何根据窗口大小改变wraplengthttk.Label?我愿意接受任何允许Label布局中的pack基于窗口大小进行换行的实现,包括它是否以某种方式使用其他属性,例如width

ttk.Label(frame, text=text_1, wraplength=500, justify=LEFT, style='my.TLabel').pack(anchor='nw')

python user-interface tkinter ttk
1个回答
0
投票

一种解决方案是对标签的<Configure>事件进行绑定。当标签调整大小时,事件将触发,您可以将wraplength重置为窗口小部件的新宽度。

这是一个简单的人为例子:

import tkinter as tk
from tkinter import ttk

class Example(object):
    def __init__(self):
        self.root = tk.Tk()
        frame = tk.Frame(self.root, bd=2, relief="groove")
        frame.pack(fill="both", expand=True, padx=2, pady=2)

        label = ttk.Label(frame, width=30, background="bisque",
                          borderwidth=1, relief="sunken", padding=4,
                          text=("Lorem ipsum dolor sit amet, consectetur " 
                                "adipiscing elit sed do eiusmod tempor "
                                "incididunt ut labore et dolore magna aliqua"))
        label.pack(side="top", fill="x", padx=10, pady=10)

        label.bind("<Configure>", self.set_label_wrap)

    def start(self):
        self.root.mainloop()

    def set_label_wrap(self, event):
        wraplength = event.width-12 # 12, to account for padding and borderwidth
        event.widget.configure(wraplength=wraplength)

Example().start()
© www.soinside.com 2019 - 2024. All rights reserved.