如果我使用 grid(),为什么当我调整 window 大小时小部件不缩放?

If I'm using grid(), why the widgets don't scale when I resize the window?

我在 Windows 7.

中使用带有 Python 3.4 的 tkinter

我以非绝对方式定位(我没有使用位置,我使用的是网格),因此,当我自动调整 window 大小时,小部件应该会缩放。然而,这并没有发生,我没有抓住要点。这是我的代码:

import tkinter as tk

class App(tk.Frame):

    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.config()
        self.grid()
        self.create_widgets()

    def config(self):
        self.master.title("Pykipedia Explorer")

    def create_widgets(self):
        self.search_label = tk.Label(self, text="Search: ")
        self.search_label.grid(row=0, column=0, sticky=tk.N+tk.SW)
        self.search_entry = tk.Entry(self)
        self.search_entry.grid(row=0, column=0, padx=60, sticky=tk.N+tk.SW)
        self.search_button = tk.Button(self, text="Explore!")
        self.search_button.grid(row=0, column=0, padx=232, sticky=tk.SW)
        self.content_area = tk.Text(self)
        self.content_area.grid(row=1, column=0)
        self.content_scroll_bar = tk.Scrollbar(self, command=self.content_area.yview)
        self.content_scroll_bar.grid(row=1, column=1, sticky=tk.NW+tk.S+tk.W)
        self.content_area["yscrollcommand"] = self.content_scroll_bar.set
        self.quit_button = tk.Button(self, text="Quit", command=self.quit)
        self.quit_button.grid(row=2, column=0, sticky=tk.SW)

def main():

    app = App()
    app.mainloop()

    return 0

if __name__ == '__main__':
    main()

为什么??

此外,I've tried to use grid_columnconfigure and grid_rowconfigure just like in this answer, and it fails miserably

您的代码中存在多个问题,这些问题共同作用以防止小部件缩放("widgets",我假设您指的是文本小部件)。

首先,您使用 gridApp 的实例放在根 window 中。但是,您还没有设置 sticky 属性,因此应用程序不会变大和变小。如果它不增长和收缩,它的内容也不会。

此外,因为您使用的是网格,所以需要为零行和零列赋予正权重,以便 tkinter 为其分配额外的 space。但是,由于这是根 window 中唯一的小部件,您可以使用 pack 并通过将对 grid 的调用替换为对 pack:

的调用来解决问题
self.pack(fill="both", expand=True)

接下来,您使用 grid 将文本小部件添加到 canvas。您还没有使用 sticky 选项,因此即使分配给它的 space 增长,该小部件也会保持在 space 的中心。您需要使用 sticky 属性告诉它 "stick" 给定区域的所有边:

self.content_area.grid(row=1, column=0, sticky="nsew")

最后,您还没有给任何列 "weight",它告诉 tkinter 如何分配额外的 space。当由 grid 管理的 window 调整大小时,任何额外的 space 都会根据它们的权重分配给行和列。默认情况下,行和列的权重为零,因此不会获得任何额外的 space.

要使文本区域随着 window 的增长而增长,您需要为第 0 列和第 1 行赋予正权重:

self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(0, weight=1)