首页 > 解决方案 > 在 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")

标签: tkinterresizescrollable

解决方案


推荐阅读