I have this code where I create n * n entries and save out the inputed data, but I want to keep the shape of the matrix, for example when I create an 2*2, the matrix should look like after the save : [[1 2][3 4]] But when I save it out it looks like: [1 2 3 4]
How can I reshape it?
from tkinter import *
import numpy as np
root = Tk()
root.geometry('800x300')
root.title('PythonExamples.org - Tkinter Example')
global e1
global numm
global my_entry
my_entry= Entry(root)
e1=Entry(root)
e1.place(x=100,y=180)
entries=[]
new_array=[]
def create():
numm=int(e1.get())
global my_entry
for x in range(numm):
for i in range(numm):
my_entry = Entry(root)
my_entry.grid(row=x, column=i)
entries.append(my_entry)
def save():
my_array = [int(entry.get()) for entry in entries]
new_array = np.asarray(my_array)
print(new_array)
create = Button(root,text='Submit',command=create).place(x=40,y=180)
save = Button(root,text='calc',command=save).place(x=40,y=210)
my_label=Label(root,text='')
root.mainloop()
CodePudding user response:
As you already have numpy.array
you can easily use .reshape
import numpy as np
my_array = [1,2,3,4]
new_array = np.asarray(my_array).reshape((2,2))
print(new_array)
output
[[1 2]
[3 4]]
Note: for demonstration purposes I use fixed value of 2
, you should use numm
instead which should be retrieved same way as in create
function.
CodePudding user response:
The create
function should be modified to:
def create():
numm = int(e1.get())
global my_entry
for x in range(numm):
row = []
for i in range(numm):
my_entry = Entry(root)
my_entry.grid(row=x, column=i)
row.append(my_entry)
entries.append(row)
The save
function should be modified to:
def save():
my_array = [[int(el.get()) for el in row] for row in entries]
new_array = np.asarray(my_array)
print(new_array)
A sample output is:
[[1 2 3]
[4 5 6]
[7 8 9]]