如何动态地将文本换行在 tkinter 标签中?

Jak*_*ödl 1 python tkinter python-3.x

当超过参数中给出的限制时,tkinter 中标签中的文本可以换行为多行wraplength

然而,这是一些像素,但我想为此使用完整的窗口宽度,并且只要用户更改窗口大小,环绕长度就应该更改。

一种方法是手动更新参数,如下所示:

def update_wraplength(id, root):
    id.configure(wraplength=root.winfo_width())
    root.after(10, lambda: update_wraplength(id,root))
Run Code Online (Sandbox Code Playgroud)

还有另一种方法可以做到这一点,也许是我不知道的参数?

rmb*_*rmb 10

每次窗口大小发生变化时,您都必须更新环绕长度。您可以检测窗口大小何时随"<Configure>"事件发生变化。

my_label.bind('<Configure>', update_wraplength)
Run Code Online (Sandbox Code Playgroud)

请记住,只有当您将标签设置为扩展到所有可用空间时,它才有效。

让我们看看您是否能理解这段代码:

import Tkinter as tk

class WrappingLabel(tk.Label):
    '''a type of Label that automatically adjusts the wrap to the size'''
    def __init__(self, master=None, **kwargs):
        tk.Label.__init__(self, master, **kwargs)
        self.bind('<Configure>', lambda e: self.config(wraplength=self.winfo_width()))

def main():
    root = tk.Tk()
    root.geometry('200x200')
    win = WrappingLabel(root, text="As in, you have a line of text in a Tkinter window, a Label. As the user drags the window narrower, the text remains unchanged until the window width means that the text gets cut off, at which point the text should wrap.")
    win.pack(expand=True, fill=tk.X)
    root.mainloop()

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)