【问题标题】:Tk grid won't resize properlyTk 网格无法正确调整大小
【发布时间】:2012-05-14 22:45:41
【问题描述】:

我正在尝试在 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()

【问题讨论】:

    标签: python grid resize tkinter


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 添加了行配置以允许垂直扩展
      【解决方案3】:

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

      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)
      

      【讨论】:

      • 我会考虑使用 pack 而不是 grid,但从我读过的内容来看,grid 也应该适用于调整小部件的大小。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 2011-03-24
      • 1970-01-01
      • 2017-01-24
      • 2018-03-15
      相关资源
      最近更新 更多