在Tkinter中文字换行文字的单行文本输入UI元素?

问题描述:

我的用户界面需要接受一行文本。但是,如果文本的长度超过UI元素的宽度,则文本应换行到下一行。在Tkinter中文字换行文字的单行文本输入UI元素?

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

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

我正在寻找中间的东西:一个接受单行文本(无换行符)的UI元素,但也会在输入溢出元素的宽度时换行。

我有什么选择?

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

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) 
+0

我觉得这个基本的想法会工作。它非常灵活。例如,可以对单词边界进行换行,限制文本长度或进行其他复杂的验证。谢谢! – 2014-09-13 17:02:08