如何从GRID传递到PACK

how to pass from GRID to PACK

我已经使用 pack 方法开发了我的 GUI 应用程序(基于 tkinter)来显示所有小部件... 现在我想创建一个“二维数组”并显示并从中获取值。 这是一个基于网格的工作解决方案。我想转换为 pack 方法的方法。 有什么建议吗?

我无法将 2 个循环(行和列)包含在 pack 方法中。

from tkinter import *
import tkinter as tk
root = Tk()
entries = []
def set_entries():
    for i in range(10):
        entries.append([])
        for j in range(10):
            entries[i].append(tk.Entry())

            entries[i][j].grid(row=i, column=j, sticky="nsew")
    tk.Button( text=" run", command=compute).grid(row=10,column=10)
def compute():
    print(entries[2][4].get())
set_entries()
root.mainloop()
button.tk.Button(text='run')
button.grid(row=10, column=10, sticky="nsew")


我不推荐使用pack,它根本不是为了制作网格而设计的。它要求每一行或每一列都有一个单独的框架,并且由您来确保小部件都具有相同的大小,使用 grid.

时不需要这样做

如果您已经在程序的其他部分使用了 pack,请仅为数组创建一个框架,并对框架中的小部件使用 grid,然后使用 pack 用于程序的其他部分。在一个程序中同时使用两者并没有错,只是不能在具有共同母版的小部件上同时使用两者。

这是一个人为的例子,展示了如何在同一个应用程序中使用 packgrid

import tkinter as tk

root = tk.Tk()
array_frame = tk.Frame(root)
toolbar = tk.Frame(root)

# use pack for the toolbar and array frame, grid inside the array frame
toolbar.pack(side="top", fill="x")
array_frame.pack(side="top", fill="both", expand=True)

run_button = tk.Button(toolbar, text="Run")
run_button.pack(side="left")

entries = {}
for i in range(5):
    for j in range(5):
        entry = tk.Entry(array_frame)
        entry.grid(row=i, column=j, sticky="nsew")
        entries[(i,j)] = entry

root.mainloop()