【发布时间】:2015-08-01 02:16:34
【问题描述】:
我正在尝试实现两个新的 GUI 子类:一个可以动态滚动和调整大小的 Frame,以及一个 Text 框,它保持其父级的宽度但将其高度调整为它有多少行文本。
Frame 似乎工作正常,但 Text 没有调整大小;当它第一次网格化时,它的高度为 1,并且仅在您调整框架大小时更新(通过单击并拖动边缘)。我一直认为我的代码越来越好,但我不知道出了什么问题。似乎 Text 类没有正确更新其高度。在ResizedText.resize() 中,当我将config 容器的高度设置为20 时,它没有正确更新... 在该语句之前和之后,高度为1,但cget["height"] 返回20。有关如何进行此操作的任何帮助更好的代码表示赞赏。谢谢。
import tkinter as tk
class ResizedText(tk.Text):
def __init__(self, parent, *args, **kwargs):
self.parent = parent
self.container_container = tk.Frame(parent, bg="blue")
self.container = tk.Frame(self.container_container, bg="red")
super().__init__(self.container, *args, **kwargs)
self.container_container.bind("<Configure>", self.resize)
self.bind("<KeyRelease>", self.resize)
def grid(self, *args, **kwargs):
self.container_container.grid(*args, **kwargs)
self.container.grid_propagate(False)
self.container.grid(row=0, column=0, sticky="nsew")
super().grid(row=0, column=0, sticky="nsew")
#self.container.grid_columnconfigure(0, weight=1)
def bind(self, *args, **kwargs):
if "add" not in kwargs: kwargs["add"] = True
super().bind(*args, **kwargs)
def resize(self, event=None):
self.container.config(width=self.container_container.winfo_width())
if self.bbox("end-1c"):
text_height = (self.bbox("end-1c")[1]+self.bbox("end-1c")[3])+4
if text_height < 20: text_height = 20
else: text_height = 20
self.container.config(height=text_height)
#after this statement, self.container.winfo_height = 1
#BUT self.container.cget("height") = 20
class ScrollableFrame(tk.Frame):
def __init__(self, parent, *args, **kwargs):
self.parent = parent
self.frame = tk.Frame(parent)
self.frame.grid_rowconfigure(0, weight=1)
self.frame.grid_columnconfigure(0, weight=1)
yscroll = tk.Scrollbar(self.frame)
yscroll.grid(row=0, column=1, sticky="ns")
self.canvas = tk.Canvas(self.frame, yscrollcommand=yscroll.set, *args,
**kwargs)
self.canvas.grid(row=0, column=0, sticky="nsew",)
yscroll.config(command=self.canvas.yview)
super().__init__(self.canvas)
self.grid_propagate(False)
self.canvas.create_window((0,0), window=self, anchor="nw")
self.frame.bind("<Configure>", self.resize_main)
self.bind("<Configure>", self.resize_canvas)
def grid(self, *args, **kwargs):
self.frame.grid(*args, **kwargs)
def resize_canvas(self, event):
self.canvas.config(scrollregion=self.canvas.bbox("all"))
def resize_main(self, event):
self.config(width=event.width, height=self.bbox("all")[3])
GUI = tk.Tk()
GUI.grid_rowconfigure(0, weight=1)
GUI.grid_columnconfigure(0, weight=1)
f = ScrollableFrame(GUI, bg="brown")
f.grid(row=0, column=0, sticky="nsew")
f.grid_columnconfigure(0, weight=1)
t = ResizedText(f, bg="blue")
t.grid(row=1, column=0, sticky="nsew")
【问题讨论】:
-
您是否尝试在更改配置后对文本小部件执行
update_idletasks()?
标签: python python-3.x textbox tkinter