6

我正在尝试在 python 中使用 Tkinter 编写一个简单的 ui,但我无法让网格中的小部件调整大小。每当我调整主窗口的大小时,条目和按钮小部件根本不会调整。

这是我的代码:

 class Application(Frame):
     def __init__(self, master=None):
         Frame.__init__(self, master, padding=(3,3,12,12))
         self.grid(sticky=N+W+E+S)
         self.createWidgets()

     def createWidgets(self):
         self.dataFileName = StringVar()
         self.fileEntry = Entry(self, textvariable=self.dataFileName)
         self.fileEntry.grid(row=0, column=0, columnspan=3, sticky=N+S+E+W)
         self.loadFileButton = Button(self, text="Load Data", command=self.loadDataClicked)
         self.loadFileButton.grid(row=0, column=3, sticky=N+S+E+W)

         self.columnconfigure(0, weight=1)
         self.columnconfigure(1, weight=1)
         self.columnconfigure(2, weight=1)

 app = Application()
 app.master.title("Sample Application")
 app.mainloop()
4

3 回答 3

15

添加一个根窗口并对其进行列配置,以便您的 Frame 小部件也可以扩展。这就是问题所在,如果您没有指定一个根窗口并且框架本身没有正确扩展,那么您将获得一个隐式根窗口。

root = Tk()
root.columnconfigure(0, weight=1)
app = Application(root)
于 2012-05-05T19:17:47.967 回答
0

一个工作示例。请注意,您必须为使用的每一列和每一行明确设置配置,但下面按钮的列跨度是一个大于显示列数的数字。

## row and column expand
top=tk.Tk()
top.rowconfigure(0, weight=1)
for col in range(5):
    top.columnconfigure(col, weight=1)
    tk.Label(top, text=str(col)).grid(row=0, column=col, sticky="nsew")

## only expands the columns from columnconfigure from above
top.rowconfigure(1, weight=1)
tk.Button(top, text="button").grid(row=1, column=0, columnspan=10, sticky="nsew")
top.mainloop()
于 2014-11-28T22:23:35.940 回答
0

我为此使用包。在大多数情况下,它就足够了。但不要混合两者!

class Application(Frame):
     def __init__(self, master=None):
         Frame.__init__(self, master)
         self.pack(fill = X, expand  =True)
         self.createWidgets()

     def createWidgets(self):
         self.dataFileName = StringVar()
         self.fileEntry = Entry(self, textvariable=self.dataFileName)
         self.fileEntry.pack(fill = X, expand = True)
         self.loadFileButton = Button(self, text="Load Data", )
         self.loadFileButton.pack(fill=X, expand = True)
于 2012-05-05T19:11:02.693 回答