Skip to main content
 首页 » 编程设计

python, tkinter之框架高度和宽度参数值无效

2025年02月15日8zhoujg

我正在尝试创建 16 个按钮,它们将完全占据窗口底部的 3/4。但是,框架高度和宽度值似乎没有任何影响。如何获得我想要的行为?

from tkinter import * 
 
 
class Application(object): 
    def __init__(self): 
        # Creating the main window 
        self.window = Tk() 
        self.window.geometry('{}x{}'.format(400, 400)) 
 
        # frame where numbered buttons will be 
        frame = Frame(self.window) 
        frame.configure(height=300, width=300) 
        frame.pack(side=BOTTOM) 
 
        # add buttons 
        for i in range(4): 
            for j in range(4): 
                Button(frame, text=str(4*i + j + 1)).grid(row=i, column=j, sticky=N+E+S+W) 
        self.window.mainloop() 
 
 
def main(): 
    app = Application() 
 
main() 

请您参考如下方法:

您所看到的行为的原因是 tkinter 小部件设计为在使用 grid 或 pack 时缩小或扩展以完全适合它们的 child 。在 99.99% 的情况下,这是完全正确的行为,因为它会导致 GUI 响应字体大小、屏幕分辨率和窗口大小的变化。

如果您的目标是将屏幕分成两部分,其中一部分占屏幕的 1/4,一部分占屏幕的 3/4,最好的解决方案是使用 grid 或place 因为它们都可以轻松设置相对大小。

我通常不推荐place,所以这里有一个使用网格的解决方案。注意 grid.rowconfigure 和 grid.columnconfigure

的使用
from tkinter import * 
 
class Application(object): 
    def __init__(self): 
        self.window = Tk() 
        self.window.geometry('{}x{}'.format(400, 400)) 
 
        self.window.grid_rowconfigure(0, weight=1) 
        self.window.grid_rowconfigure(1, weight=3) 
        self.window.grid_columnconfigure(0, weight=1) 
 
        frame = Frame(self.window, background="pink") 
        frame.grid(row=1, column=0, sticky="nsew") 
 
        for row in range(4): 
            frame.grid_rowconfigure(row, weight=1) 
        for column in range(4): 
            frame.grid_columnconfigure(column, weight=1) 
 
        # add buttons 
        for i in range(4): 
            for j in range(4): 
                button = Button(frame, text=str(4*i + j + 1)) 
                button.grid(row=i, column=j, sticky=N+E+S+W) 
        self.window.mainloop() 
 
 
def main(): 
    app = Application() 
 
main() 

在此示例中,根窗口中的第 0 行(零)可用于任何您想要的内容。 Tkinter 将尽力使 GUI 的那部分始终成为窗口高度的 1/4。我建议在该行中放置一个框架,然后在该框架内放置任何其他小部件。