如何将这些输出转换为矩阵形式

2024-10-04 01:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

我编写了一个代码来显示4x4 tkinter条目小部件。因此,当我在每个输入框中输入值并按下“矩阵形式”按钮打印输出后,它在shell中打印如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

我想实现的是按以下格式打印:

[[1,2,3,4],
 [5,6,7,8],
 [9,10,11,12],
 [13,14,15,16]]

下面是我的代码:

from tkinter import *
import numpy as np
import tkinter.font
import tkinter.ttk as ttk

fourbyfour = Tk()
fourbyfour.wm_geometry("420x400+0+0")
fourbyfour.wm_title("4X4 Matrix Calc")
fourbyfour.focus_set()
fourbyfour.grab_set()

myFont = tkinter.font.Font(family = 'Helvetica' , size = 12, weight = 'bold')

def getmatrix():
    for row in rows:
        for col in row:
            m = col.get()
            print(m)

rows = []
for i in range(4):
    cols = []
    for j in range(4):
        e = Entry(fourbyfour,width=10,font=myFont,bd=5)
        e.grid(row=i, column=j, sticky=NSEW)
        cols.append(e)
    rows.append(cols)

Calculate_2 = Button(fourbyfour, text = "Matrix Form",
                 font = myFont, bd=4, command = getmatrix,
                 bg = 'light blue', height = 2 ,width = 8)
Calculate_2.grid(row=5, column=2)

Tags: 代码inimportfortkinterasmatrixrows