I already developed my GUI app (based on tkinter) using the pack method to show all widgets... Now I want to create a '2d array' and show and get values from it. here is a working solution based on grid. method that I want to convert to pack method. any suggestion?
I couldn't include the 2 loops (rows and columns) with the pack method.
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")
I don't recommend using pack
, it's simply not designed to make a grid. It requires a separate frame for each row or for each column, and it's up to you to make sure the widgets are all the same size, which you don't need when using grid
.
If you're already using pack
in other parts of the program, create a frame just for the array and use grid
for the widgets in the frame, and then use pack
for the other parts of your program. There's nothing wrong with using both in a program, you just can't use both on widgets that have a common master.
Here's a contrived example, showing how you can use pack
and grid
in the same application:
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()