使用 tkinter 调整 window 大小和其中的文本长度

Adjust the window size with the text length in it with tkinter

您知道是否可以自动调整 window 的宽度以匹配其中文本的长度吗? 例如, 很合适,但在 中,文本超出了 window.

或者如果更好,是否可以换行以适合 window 中的文本?

PS: 在我的 window 中插入文本 我正在使用 ttk.Label()

尝试使用标签的 wraplength 属性

import tkinter as tk

root = tk.Tk()
tk.Label(root,width=40,text="This is going to be far too long to fit on the screen that I have chosen").grid()
tk.Label(root,width=40,wraplength=100,text="This is going to be far too long to fit on the screen that I have chosen but will wrap").grid()

root.mainloop()

这个行为对我来说似乎有点不一致,但它应该以 40 个字符换行。

如果您不想将 window 的大小显式设置为特定大小,那么您可以

window.geometry("")

它会自动调整大小以适应 window

的内容