[英]How to dynamically wrap label text in tkinter with .bind and <Configure>
[英]How to wrap the text in a tkinter label dynamically?
當超過參數wraplength
中給定的限制時,tkinter 中的 label 中的文本可以換行成多行。
但是,這是多個像素,但是,我想為此使用完整的 window 寬度,並且每當用戶更改 window 大小時,環繞長度都應該改變。
一種方法是手動更新參數,如下所示:
def update_wraplength(id, root):
id.configure(wraplength=root.winfo_width())
root.after(10, lambda: update_wraplength(id,root))
還有另一種方法可以做到這一點,也許是我不知道的參數?
每次 window 大小更改時,您都必須更新包裹長度。 您可以檢測 window 大小何時隨"<Configure>"
事件發生變化。
my_label.bind('<Configure>', update_wraplength)
請記住,它僅在您將 Label 設置為擴展到所有可用空間時才有效。
讓我們看看你是否能理解這段代碼:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.