2

grid()我有一个框架中带有网格的应用程序,并且在使用 all和 no时遇到了问题pack()
我已经简化了我的应用程序来隔离这个问题。

使用pack()它可以正确调整大小,但grid()不会。

我究竟做错了什么?

下面是两个例子:

  1. 有一些pack()

    from tkinter import *
    from tkinter import ttk
    
    class App(Frame):
        def __init__(self, parent):
            mframe = Frame.__init__(self, parent)
            self.pack(fill = 'both', expand = True)
            ttk.Sizegrip(mframe).pack(side = 'right')
    
            self.columnconfigure(0, weight = 1)
            self.rowconfigure(0, weight = 1)
    
            Text(self, width = 20, height = 2).grid(row = 0, column = 0, sticky = 'nsew')
    
    root = Tk()
    App(root)
    root.mainloop()
    
  2. 只有grid()

    from tkinter import *
    from tkinter import ttk
    
    class App(Frame):
        def __init__(self, parent):
            mframe = Frame.__init__(self, parent)
            self.grid(row = 0, column = 0, sticky = 'nsew')
            ttk.Sizegrip(root).grid(row = 1, sticky = 'se')
    
            self.columnconfigure(0, weight = 1)
            self.rowconfigure(0, weight = 1)
    
            Text(self, width = 20, height = 2).grid(row = 0, column = 0, sticky = 'nsew')
    
    root = Tk()
    App(root)
    root.mainloop()
    

.

4

1 回答 1

0

问题是您使用网格将App框架放置在其父级中,但您没有配置父级中的行和列的权重。如果您使用网格,则必须配置行和列权重以获得正确的调整大小行为。

您需要添加以下内容:

parent.rowconfigure(0, weight=1)
parent.columnconfigure(0, weight=1)

但是,我建议您不要self.grid课堂内拨打电话。让创建小部件的函数决定该小部件的去向是更好的设计。虽然在这个小例子中它并不重要,但一旦你开始制作更复杂的 GUI,它就会很重要。

此外,混合网格和包是非常好的,只要您不在同一个主窗口中使用它们。由于 App 是根小部件中的唯一小部件,因此在这种情况下使用 pack 会更容易一些,因为您不必记住配置行和列。我会改变你的代码来做到这一点:

root = Tk()
App(root).pack(side="top", fill="both", expand=True)
root.mainloop()

...然后删除对initself.grid函数内部的调用,使大小网格成为框架的子级而不是根

于 2013-10-19T14:02:46.407 回答