我有一個 19x5 矩陣,默認情況下只有零。我想使用 tkinter 創建一個視窗,該視窗顯示一個空的 19x5 矩陣,用戶將填充值(正實數)或留空。在這種情況下,我希望空白輸入保持為零,輸入值以替換相應位置的零,并保存新矩陣。
import numpy as np
import PySimpleGUI as sg
from tkinter import *
demand = np.zeros((19,5))
uj5u.com熱心網友回復:
tkinter必須Entry()獲取文本,您可以將其與布局管理器一起使用.grid(row, column)來創建matrix/table與許多Entry(). 您可以使用兩個for-回圈將小部件放在行和列中。
但是您可以在標準視窗中執行此操作tkinter.Tk()- 而不是在對話框中。
您必須添加從 all 中獲取值Entry()并放入 numpy 陣列的代碼。最好將此代碼分配給Button().

import numpy as np
import tkinter as tk # PEP8: `import *` is not preferred
# --- functions ---
def get_data():
for r, row in enumerate(all_entries):
for c, entry in enumerate(row):
text = entry.get()
demand[r,c] = float(text)
print(demand)
# --- main ---
rows = 19
cols = 5
demand = np.zeros((rows, cols))
window = tk.Tk()
all_entries = []
for r in range(rows):
entries_row = []
for c in range(cols):
e = tk.Entry(window, width=5) # 5 chars
e.insert('end', 0)
e.grid(row=r, column=c)
entries_row.append(e)
all_entries.append(entries_row)
b = tk.Button(window, text='GET DATA', command=get_data)
b.grid(row=rows 1, column=0, columnspan=cols)
window.mainloop()
編輯:
您還可以使用Label為行和列添加數字

import numpy as np
import tkinter as tk # PEP8: `import *` is not preferred
# --- functions ---
def get_data():
for r, row in enumerate(all_entries):
for c, entry in enumerate(row):
text = entry.get()
demand[r,c] = float(text)
print(demand)
# --- main ---
rows = 19
cols = 5
demand = np.zeros((rows, cols))
window = tk.Tk()
for c in range(cols):
l = tk.Label(window, text=str(c))
l.grid(row=0, column=c 1)
all_entries = []
for r in range(rows):
entries_row = []
l = tk.Label(window, text=str(r 1))
l.grid(row=r 1, column=0)
for c in range(cols):
e = tk.Entry(window, width=5) # 5 chars
e.insert('end', 0)
e.grid(row=r 1, column=c 1)
entries_row.append(e)
all_entries.append(entries_row)
b = tk.Button(window, text='GET DATA', command=get_data)
b.grid(row=rows 1, column=0, columnspan=cols)
window.mainloop()
如果您想要更復雜的東西(具有更多功能),那么您可以使用pandastable您可以在DataExplorer中看到的
更多在我的博客文章中:Tkinter PandasTable 示例
順便說一句: PEP 8——Python 代碼風格指南
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/433835.html
