【问题标题】:How to wrap the text in a tkinter label dynamically?如何动态地将文本包装在 tkinter 标签中?
【发布时间】:2020-06-20 11:57:50
【问题描述】:

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

但是,这是一个像素数,但我想为此使用整个窗口宽度,并且每当用户更改窗口大小时,换行长度都应该改变。

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

def update_wraplength(id, root):
    id.configure(wraplength=root.winfo_width())
    root.after(10, lambda: update_wraplength(id,root))

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

【问题讨论】:

标签: python python-3.x tkinter


【解决方案1】:

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

my_label.bind('<Configure>', update_wraplength)

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

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

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()

【讨论】:

  • 谢谢你的例子。对于我的用例来说,创建一个类似乎是最优雅的方式。
  • 太棒了!评论也用于要求澄清、留下建设性的批评或添加相关但次要的附加信息——而不是用于社交。如果您想说“谢谢”,请投票或接受答案:)
  • 如果您遇到收缩窗口时成功重新包装但展开时没有成功重新包装的问题,请注意您必须有fill=tk.X pack 命令中的参数! (这就是“它只有在您将标签设置为扩展到所有可用空间时才有效”的意思,但因为它只工作了一半,所以我很困惑。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-28
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多