首页 文章

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

提问于
浏览
4

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

用例是一个对话框,需要完整地呈现一行多行文本(指令),而不会剪切文本或使用滚动条 . 父容器将具有足够的垂直空间以容纳窄宽度 .

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

我应该看一下Text小部件吗?如果是这样,是否可以隐藏文本小部件的边框,以便我可以将其用作wordwrap的多行标签?

这里's a prototype of how one might do what I described above. It was inspired by Bryan Oakley'提示使用Text小部件和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()

3 回答

  • 2

    不,Tk没有内置自动自动换行标签的功能 . 但是,它可以通过绑定到标签的 <Configure> 事件并调整包装长度来实现 . 每次调整标签窗口小部件时,都会触发此绑定 .

    正如您所建议的那样,另一个选项是使用文本小部件 . 如果您愿意,可以完全关闭边界 . 当我想要包装文字的教学文本时,这一直是我的选择 .

  • 3

    使用Message widget

    Message小部件是Label的变体,旨在显示多行消息 . 消息窗口小部件可以包装文本,并调整其宽度以维持给定的宽高比 .

  • 1

    这是代码:

    entry = Label(self, text=text,
        anchor=NW, justify=LEFT,
        relief=RIDGE, bd=2)
    def y(event, entry=entry):
      # FIXME: make this a global method, to prevent function object creation
      # for every label.
      pad = 0
      pad += int(str(entry['bd']))
      pad += int(str(entry['padx']))
      pad *= 2
      entry.configure(wraplength = event.width - pad)
    entry.bind("<Configure>", y )
    

相关问题