Tkinter将文本大小调整为内容

Squ*_*361 2 python tkinter

是否可以调整Tkinter文本小部件以适应其内容?

即:如果我放一行文字它会收缩,但如果我放了5行它会增长

smo*_*ont 6

我想到实现这一点的唯一方法是每次用户在Text小部件中输入文本时计算宽度和高度,然后将小部件的大小设置为该值.但这里的限制是只有单倍间距的字体才能正常工作,但无论如何它仍然是:

import Tkinter

class TkExample(Tkinter.Frame):
   def __init__(self, parent):
      Tkinter.Frame.__init__(self, parent)
      self.init_ui()

   def init_ui(self):
      self.pack()
      text_box = Tkinter.Text(self)
      text_box.pack()
      text_box.bind("<Key>", self.update_size)

   def update_size(self, event):
      widget_width = 0
      widget_height = float(event.widget.index(Tkinter.END))
      for line in event.widget.get("1.0", Tkinter.END).split("\n"):
         if len(line) > widget_width:
            widget_width = len(line)+1
      event.widget.config(width=widget_width, height=widget_height)

if __name__ == '__main__':
    root = Tkinter.Tk()
    TkExample(root)
    root.mainloop()
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用 `font_measure` 来获取可变宽度字体中一行文本的实际宽度。此外,这会受到以下事实的影响:您的绑定在插入文本之前触发。您需要绑定 `&lt;KeyRelease&gt;` 或摆弄绑定标签,以便您的绑定发生在类绑定之后。 (3认同)

JD *_*ham 6

在谷歌搜索的顶部找到了这个线程,因此,也许需要这个的人会找到它。即使经过几个小时的搜索也找不到答案。这就是我想出的HACK。

我想要一个弹出窗口,它能够在文本小部件中的任何未知但预先确定的文本周围正确地调整自身形状,而不是用户输入。此外,文本小部件需要在其文本内容周围正确地进行形状调整。

Atkinter.Label效果很好,但它没有tkinter.Text.tag_configuretkinter.Text.tag_bind我需要用 tkinter 的富文本标签替换一些 HTML 标签。  tkinter.Text有富文本标签,但不能很好地扩展,虽然可以tkinter.Label很好地扩展,但没有富文本标签。此外,我只是讨厌滚动条和自动换行,除非确实需要它们。这正是我想要的。不过,这只是本论坛的一个非常简单的工作摘要。适用于任何字体。仅在 Ubuntu 13.10 (Linux) 中使用 Python 3.3 进行了测试。

#!/usr/bin/env python3

import tkinter as tk

class MyFrame(tk.Frame):
    def __init__(self):
        tk.Frame.__init__(self)

        root = self.master
        root.title("My Window Title")

        # Pack Frame into root window and make it expand in "both" x and y
        self.pack(side="top", fill="both", expand=True, padx=10, pady=10)
        # Statistical weight of 1 = 100% for cell (0, 0) to expand 100%
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        # The string text
        text = """Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed
diam nonummy nibh euismod tincidunt ut laoreet dolore magna
aliquam erat volutpat. Ut wisi enim ad minim veniam, quis
nostrud exerci tation ullamcorper suscipit lobortis nisl ut
aliquip ex ea commodo consequat. Duis autem vel eum iriure
dolor in hendrerit in vulputate velit esse molestie consequat,
vel illum dolore eu feugiat nulla facilisis at vero eros et
accumsan et iusto odio dignissim qui blandit praesent luptatum
zzril delenit augue duis dolore te feugait nulla facilisi. Nam
liber tempor cum soluta nobis eleifend option congue nihil
imperdiet doming id quod mazim placerat facer possim assum.
Typi non habent claritatem insitam; est usus legentis in iis qui
facit eorum claritatem. Investigationes demonstraverunt lectores
legere me lius quod ii legunt saepius. Claritas est etiam
processus dynamicus, qui sequitur mutationem consuetudium
lectorum. Mirum est notare quam littera gothica, quam nunc
putamus parum claram, anteposuerit litterarum formas
humanitatis per seacula quarta decima et quinta decima. Eodem
modo typi, qui nunc nobis videntur parum clari, fiant sollemnes
in futurum."""

        # Add a tk.Text widget to Frame (self) and its configuration
        textwidget = tk.Text(self, wrap="none", font=("Comic Sans MS", 12),
                             padx=10, pady=10)
        textwidget.grid(row=0, column=0, sticky="nesw")
        # Add the text to textwidget and disable editing
        textwidget.insert(tk.END, text)
        textwidget.config(state=tk.DISABLED)

        # Here is where the HACK begins
        def is_scroll(wh, lower, upper):
            nonlocal size
            size[wh][0] = upper < '1.0' or lower > '0.0'
            size[wh][1] += 20 * size[wh][0] # += 1 for accuracy but slower
        # Call the is_scroll function when textwidget scrolls
        textwidget.config(xscrollcommand=lambda *args: is_scroll('w', *args),
                          yscrollcommand=lambda *args: is_scroll('h', *args))

        # Add a tk.Button to the Frame (self) and its configuration
        tk.Button(self, text="OK", command=self.quit).grid(row=1, column=0,
                                                           sticky="we")

        # For reasons of magic, hide root window NOW before updating
        root.withdraw()

        # Initially, make root window a minimum of 50 x 50 just for kicks
        root.geometry('50x50')
        size = {'w': [False, 50], 'h': [False, 50]}
        # Update to trigger the is_scroll function
        root.update()
        while size['w'][0] or size['h'][0]:
            # If here, we need to update the size of the root window
            root.geometry('{}x{}'.format(size['w'][1], size['h'][1]))
            root.update()

        # Center root window on mouse pointer
        x, y = root.winfo_pointerxy()
        root.geometry('+{}+{}'.format(x-size['w'][1]//2, y-size['h'][1]//2))

        # Now reveal the root window in all its glory
        root.deiconify()

        # Print textwidget dimensions to the console
        print(textwidget.winfo_width(), textwidget.winfo_height())

def main():
    """Show main window."""
    MyFrame().mainloop()

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

说明:  诀窍是不要去尝试直接扩展或缩小文本小部件,这是徒劳的。答案有点违反直觉,因为人们的第一个想法是直接进入该文本小部件并对其执行某些操作。相反,展开根(最外层)窗口(在本例中为self.master),并保留 Text 小部件。十分简单。

将文本小部件粘 ( "nesw") 到框架中,该框架在根窗口中打包为 100% 扩展。随着根窗口的扩展,其中的框架和文本小部件也会扩展。但是,当您扩展根窗口时,请测试文本小部件的、 和lower的 和upper边界是否消失(不再滚动)。这些命令将参数作为百分位数发送给滚动条所需的回调函数,通常是. 但是,我们使用这些命令是因为我们根本不需要滚动条或任何滚动。我们想要完美契合。xscrollcommandyscrollcommandloweruppertkinter.Scrollbar.set

如果lowerupper边界消失了(下限 <= 0.0 且上限 >= 1.0),这意味着我们的 Text 小部件周围有一个完美适合的窗口,该窗口也完美适合其文本内容。田田!

添加了一个按钮来演示即使添加了其他小部件它仍然可以正常工作。删除一些文字,看看它的形状是否仍然完美。