【发布时间】:2020-04-11 18:56:12
【问题描述】:
在画布中加载新框架后,滚动条不适合内容。
如果我手动调整窗口大小,滚动条会适合内容。
加载框架时如何强制滚动条适应内容?
这是重现我的问题的代码:
from tkinter import *
class MyApp:
def __init__(self):
self.root = Tk()
self.mainframe = Frame(self.root)
self.mainframe.pack(fill=BOTH, expand=True)
self.mainframe.columnconfigure(0, weight=1)
self.contentCanvas = Canvas(self.mainframe)
self.contentCanvas.grid(sticky=N + S + W + E)
self.horizontalBar = Scrollbar(self.mainframe, orient=HORIZONTAL)
self.horizontalBar.grid(rowspan=2, sticky=W + E + S)
self.horizontalBar.config(command=self.contentCanvas.xview)
self.contentCanvas.config(xscrollcommand=self.horizontalBar.set)
self.contentFrame = Frame(self.contentCanvas)
self.content = Frame(self.contentFrame)
self.content.grid()
Button(self.content, text="Load Long Content", command=self.loadLongContent).grid()
self.contentCanvas.bind("<Configure>", lambda e: self.contentCanvas.configure(scrollregion=self.contentFrame.bbox("all")))
self.contentCanvas.create_window((0, 0), window=self.contentFrame, anchor="nw")
def run(self):
self.root.mainloop()
def loadContentFrame(self, frame):
self.content.grid_forget()
self.content.destroy()
self.content = frame
self.content.grid()
def loadLongContent(self):
longFrame = Frame(self.contentFrame)
for i in range(100):
Label(longFrame, text=i*i).grid(row=0, column=i)
self.loadContentFrame(longFrame)
if __name__ == "__main__":
app = MyApp()
app.run()
图片:
加载新内容之前:
加载新内容后:
稍微调整窗口大小后:
【问题讨论】:
-
如果调整大小触发了更正,您可以调用:
self.root.geometry("500x500")强制调整大小,只需调整合适的高度和稍微增加宽度