Tkinter 网格几何尺寸调整问题

问题描述

调整窗口大小时,右侧面板中的浏览按钮被分离。我希望整个事情都保持在一起,并平等地调整大小。

import tkinter as tk
from tkinter import ttk
from tkinter import *

class AppLayout(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        
        
        self.masterPane = tk.PanedWindow(self )
        self.leftPane   = tk.Frame(self.masterPane,relief = 'raised',bg='black',width =100)
        self.masterPane.add(self.leftPane)
        
        self.rightPane   = tk.Frame(self.masterPane)
        self.masterPane.add(self.rightPane)
        
        self.masterPane.pack(fill = 'both',expand = True)
        


        name_entry    = tk.Entry(self.rightPane,font =('calibre',10,'normal'))
        browse_Button = tk.Button(self.rightPane,text = 'browse')
        Upload_Button = tk.Button(self.rightPane,text = 'Upload')
        
        name_entry.grid(row=1,column=1)
        browse_Button.grid(row=1,column=2)
        Upload_Button.grid(row=1,column=1,pady =(50,0))
        

        self.rightPane.columnconfigure(1,weight=1)
        self.rightPane.rowconfigure(1,weight=1)


app = AppLayout()
app.mainloop()

解决方法

你需要改变四件事:

  • 不要重复导入 tkinter。从中导入 * 就足够了。
  • 将 rightPane 的第二列配置为在调整窗口大小时扩展。
  • 通过将 sticky=W 添加到 .grid() 方法,将按钮置于第二列的西侧 (W)。
  • 将 Entry 小部件粘贴到第 1 列的东侧和西侧。因此,当此列扩展时,它会变宽。

使用以下代码,它可以工作。 您还可以在框架小部件上使用 .colmnconfigure().rowconfigure() 方法来指定其他窗格如何扩展以及应用如何垂直调整大小。

from tkinter import ttk
from tkinter import *

class AppLayout(Tk):
    def __init__(self):
        Tk.__init__(self)

        self.masterPane = PanedWindow(self )
        self.leftPane   = Frame(self.masterPane,relief = 'raised',bg='black',width =100)
        self.masterPane.add(self.leftPane)
        
        self.rightPane   = Frame(self.masterPane)
        self.rightPane.columnconfigure(2,weight=1)
        self.masterPane.add(self.rightPane)
        
        self.masterPane.pack(fill = 'both',expand = True)
        
        name_entry    = Entry(self.rightPane,font =('calibre',10,'normal'))
        Browse_Button = Button(self.rightPane,text = 'Browse')
        Upload_Button = Button(self.rightPane,text = 'Upload')
        
        name_entry.grid(row=1,column=1,sticky=W+E)
        Browse_Button.grid(row=1,column=2,sticky=W)
        Upload_Button.grid(row=1,pady =(50,0))

        self.rightPane.columnconfigure(1,weight=1)
        self.rightPane.rowconfigure(1,weight=1)


app = AppLayout()
app.mainloop()