gpt4 book ai didi

python - 使用自动换行创建可调整大小/多行 Tkinter/ttk 标签

转载 作者:可可西里 更新时间:2023-11-01 13:59:45 27 4
gpt4 key购买 nike

是否可以创建一个多行标签,其自动换行的大小与其父级的宽度同步?换句话说,当您更改记事本窗口的宽度时,记事本的自动换行行为。

用例是一个对话框,需要完整地呈现一段多行文本(说明),而不需要剪裁文本或使用滚动条。父容器将有足够的垂直空间来容纳较窄的宽度。

我一直在试验 Tkinter Label 和 Message 小部件以及 ttk Label 小部件但没有成功。似乎我需要硬编码像素 wraplength 值,而不是让这些控件在文本到达容器的右边缘时自动自动换行。当然 Tkinters 几何管理器可以帮助我自动调整标签的大小并相应地更新它们的 wraplength 值?

我应该查看文本小部件吗?如果是这样,是否可以隐藏文本小部件的边框,以便我可以将其用作带自动换行的多行标签?

这是一个原型(prototype),说明如何执行我上面描述的操作。它的灵感来自 Bryan Oakley 的使用文本小部件的技巧和 Stackoverflow 上的以下帖子: In python's tkinter, how can I make a Label such that you can select the text with the mouse?

from Tkinter import *
master = Tk()

text = """
If tkinter is 8.5 or above you'll want the selection background to appear like it does when the widget is activated. Comment this out for older versions of Tkinter.

This is even more text.

The final line of our auto-wrapping label that supports clipboard copy.
""".strip()

frameLabel = Frame( master, padx=20, pady=20 )
frameLabel.pack()
w = Text( frameLabel, wrap='word', font='Arial 12 italic' )
w.insert( 1.0, text )
w.pack()

# - have selection background appear like it does when the widget is activated (Tkinter 8.5+)
# - have label background color match its parent background color via .cget('bg')
# - set relief='flat' to hide Text control borders
# - set state='disabled' to block changes to text (while still allowing selection/clipboard copy)
w.configure( bg=master.cget('bg'), relief='flat', state='disabled' )

mainloop()

最佳答案

使用Message widget :

The Message widget is a variant of the Label, designed to display multiline messages. The message widget can wrap text, and adjust its width to maintain a given aspect ratio.

关于python - 使用自动换行创建可调整大小/多行 Tkinter/ttk 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4011354/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com