有沒有這樣的小部件,但你可以這樣做:
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)
我覺得這個基本的想法會工作。它非常靈活。例如,可以對單詞邊界進行換行,限制文本長度或進行其他複雜的驗證。謝謝! – 2014-09-13 17:02:08