简体   繁体   English

Tk网格无法正常调整大小

[英]Tk grid won't resize properly

I'm trying to write a simple ui with Tkinter in python and I cannot get the widgets within a grid to resize. 我正在尝试用python中的Tkinter编写一个简单的ui,我无法在网格中获取小部件来调整大小。 Whenever I resize the main window the entry and button widgets do not adjust at all. 每当我调整主窗口的大小时,入口和按钮小部件根本不会调整。

Here is my code: 这是我的代码:

 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()

Add a root window and columnconfigure it so that your Frame widget expands too. 添加根窗口并对其进行配置,以便您的Frame小部件也可以展开。 That's the problem, you've got an implicit root window if you don't specify one and the frame itself is what's not expanding properly. 这就是问题,如果你没有指定一个隐藏的根窗口,那么框架本身就是没有正确扩展的东西。

root = Tk()
root.columnconfigure(0, weight=1)
app = Application(root)

I use pack for this. 我用这个包。 In most cases it is sufficient. 在大多数情况下,这就足够了。 But do not mix both! 但不要混合两者!

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)

A working example. 一个工作的例子。 Note that you have to explicitly set the configure for each column and row used, but columnspan for the button below is a number greater than the number of displayed columns. 请注意,您必须为使用的每个列和行显式设置configure,但下面按钮的columnspan是一个大于显示列数的数字。

## 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM