tkinter - 在 tkinter 中使用可滚动框架时初始化具有正确尺寸的窗口
问题描述
我有以下代码,可滚动框架工作得很好(感谢这里的所有其他海报)。现在有一件事让我感到困惑:我如何管理代码以打开如此大小的应用程序窗口,以使其适合其中的所有内容?
无论我做什么或尝试,应用程序窗口总是以一些默认大小(我猜它的画布默认大小)打开,而不是适合其内容。在下面的示例中,我添加了 20 个文本标签来显示行为。创建的窗口仅适合这些标签中的 14 个。其他的都在那里并且它是可滚动的,但我希望启动窗口立即适合所有内容。
我想首先避免为 tk() 窗口设置固定大小。老实说,我并不完全理解我从其他线程收集的代码,但除了我刚刚描述的问题之外,一切正常。
import tkinter as tk
from tkinter import ttk
class mainWindow():
''' Master class of the gui window. '''
def __init__(self,appName):
self.window = tk.Tk()
self.window.title(appName)
self.canvas = tk.Canvas(self.window)
self.GlobalContentFrame = tk.Frame(self.canvas, background="#ffffff")
self.vsb = tk.Scrollbar(self.window, orient="vertical", command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.vsb.set)
self.vsb.pack(side=tk.RIGHT, fill="y")
self.canvas.pack(side=tk.LEFT, fill="both",expand=1)
self.canvas.create_window((1,1), window=self.GlobalContentFrame, anchor="nw",tags="self.GlobalContentFrame")
self.GlobalContentFrame.bind("<Configure>", self.onFrameConfigure)
self.canvas.bind("<Configure>", self.onCanvasConfigure)
for p in range(20):
label = ttk.Label(self.GlobalContentFrame,text="test")
label.grid(column=0,row=p,sticky=tk.EW)
self.window.mainloop()
def onCanvasConfigure(self,event):
w,h = event.width, event.height
natural = self.GlobalContentFrame.winfo_reqwidth()
self.canvas.itemconfigure("inner", width= w if w>natural else natural)
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def onFrameConfigure(self, event):
'''Reset the scroll region to encompass the inner frame'''
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
appWin = mainWindow("test")
解决方案
推荐阅读
- swift - Swift 以编程方式创建一个 unwind segue
- r - 如何考虑合并/加入添加多余的行?
- reactjs - useState 和函数 - 盖茨比
- sql-server - 带有外键约束的 INSERT INTO SELECT 查询在 SQL Server 中不起作用
- python - Python excel生成在Windows中失败
- robotframework - 用“运行关键字如果”给出的关键字没有被执行
- django - Djangop Heroku,发送电子邮件时,我们收到错误500,如何解决?
- c# - Unity - 如何从场景 1 传输对象并在场景 2 中实例化它?
- reactjs - 使用 redux 响应身份验证
- discord.py-rewrite - 如何获得具有特定权限的所有角色