【问题标题】:Arranging size of a frame in tkinter在 tkinter 中安排帧的大小
【发布时间】:2026-02-17 05:45:02
【问题描述】:

我正在为我的应用程序制作一个简单的工具箱。我使用了类方法,它继承了Frame 作为它的超类。在我的主文件中,我导入了这个类。

这将是一个主窗口,所有小部件都在其中。但是有个问题,这里是源码:

from tkinter import *

class ToolBox(Frame):
    def __init__(self, master=None,
                 width=100, height=300):
        Frame.__init__(self, master,
                       width=100, height=300)
        self.pack()
        Button(self, text="B").grid(row=0, sticky=(N,E,W,S))
        Button(self, text="B").grid(row=0, column=1, sticky=(N,E,W,S))
        Button(self, text="B").grid(row=1, column=0,sticky=(N,E,W,S))
        Button(self, text="B").grid(row=1, column=1, sticky=(N,E,W,S))
        Button(self, text="B").grid(row=2, column=0, sticky=(N,E,W,S))
        Button(self, text="B").grid(row=2, column=1, sticky=(N,E,W,S))

我在这里导入这个:

from tkinter import *
import toolbox as tl

root = Tk()

frame = Frame(root, width=400, height=400)
frame.pack()
tl.ToolBox(frame).pack()

root.mainloop()

主窗口,即拥有frameroot,宽度和高度必须为400。但它出现在我的工具箱的尺寸中。我希望工具箱位于主窗口中。我该如何解决这个问题?

【问题讨论】:

    标签: python-3.x tkinter


    【解决方案1】:

    您可以使用geometry 方法强制根窗口具有特定尺寸。

    root = Tk()
    root.geometry("400x400")
    

    如果您还希望按钮均匀拉伸以填充整个根窗口,则需要做两件事:

    1. 调用 rowconfigurecolumnconfigure 来设置作为按钮父级的根和每个框架的权重。
    2. 为作为根目录的每个按钮和框架指定粘性参数。

    这是一个例子。我删除了您的frame Frame,因为它似乎没有做任何事情。毕竟 Toolbox 已经是一个框架了,把一个框架放在一个框架里面也没多大意义。

    from tkinter import *
    
    class ToolBox(Frame):
        def __init__(self, master=None,
                     width=100, height=300):
            Frame.__init__(self, master,
                           width=width, height=height)
            for i in range(2):
                self.grid_columnconfigure(i, weight=1)
            for j in range(3):
                self.grid_rowconfigure(j, weight=1)
    
            Button(self, text="B").grid(row=0, sticky=(N,E,W,S))
            Button(self, text="B").grid(row=0, column=1, sticky=(N,E,W,S))
            Button(self, text="B").grid(row=1, column=0,sticky=(N,E,W,S))
            Button(self, text="B").grid(row=1, column=1, sticky=(N,E,W,S))
            Button(self, text="B").grid(row=2, column=0, sticky=(N,E,W,S))
            Button(self, text="B").grid(row=2, column=1, sticky=(N,E,W,S))
    
    root = Tk()
    root.geometry("400x400")
    
    root.grid_rowconfigure(0, weight=1)
    root.grid_columnconfigure(0, weight=1)
    
    ToolBox(root).grid(sticky="news")
    
    root.mainloop()
    

    现在您的根的大小已正确,并且您的按钮会拉伸以填充它。

    【讨论】: