简体   繁体   中英

When using the pack layout of Tkinter, how can I have a Label's wraplength be equal to the width of the window when it is resized?

I'm using the pack layout of Tkinter , and I allow the application window to be resized.

What I can't figure out is how to have the wraplength of a ttk.Label be variable based on window size? I'm open to any implementation that allows a Label in the pack layout to wrap based on window size, including if it somehow uses other attributes, such as width .

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

One solution is to put a binding on the <Configure> event for the label. When the label resizes, the event will fire and you can reset the wraplength to be the new width of the widget.

Here's a simple contrived example:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM