单行文本输入UI元素,用于包装Tkinter中的文本?

时间:2014-09-13 03:03:03

标签: python tkinter word-wrap

我的UI需要接受一行文字。但是,如果文本的长度超过了UI元素的宽度,则文本应该换行到下一行。

Tkinter Entry类提供了我在接受单行文本时所寻找的内容。但是,如果文本超出元素的宽度,则文本不会被包装。相反,它向左滚动。这可以防止用户看到前几个字符是什么。

Tkinter Text类支持自动换行,但它也允许用户输入换行符。我的文字需要输入一行。

我正在寻找介于两者之间的东西:一个接受单行文本的UI元素(没有换行符),但当输入溢出元素的宽度时也会换行。

我有什么选择?

1 个答案:

答案 0 :(得分:4)

没有这样的小部件,但你可以这样做:

import tkinter as tk

class ResizableText:
    def __init__(self, text_max_width=20):
        self.text_width = text_max_width
        self.root = tk.Tk()

        self.text = tk.Text(self.root, width=self.text_width, height=1)
        self.text.pack(expand=True)

        self.text.bind("<Key>", self.check_key)
        self.text.bind("<KeyRelease>", self.update_width)

        self.root.mainloop()

    def check_key(self, event):
        # Ignore the 'Return' key
        if event.keysym == "Return":
            return "break"

    def update_width(self, event):
        # Get text content; ignore the last character (always a newline)
        text = self.text.get(1.0, tk.END)[:-1]
        # Calculate needed number of lines (=height)
        lines = (len(text)-1) // self.text_width + 1
        # Apply changes on the widget
        self.text.configure(height=lines)