簡體   English   中英

我如何使用 tkinter 從用戶在對話框中的輸入創建矩陣

[英]How can i create a matrix from user's input in dialog box using tkinter

我有一個 19x5 矩陣,默認情況下只有零。 我想使用 tkinter 創建一個 window,它顯示一個空的 19x5 矩陣,用戶將用值(正實數)填充或留空。 在那種情況下,我希望空白輸入保持零,輸入值替換相應位置的零,並保存新矩陣。

import numpy as np
import PySimpleGUI as sg
from tkinter import *

demand = np.zeros((19,5))

tkinterEntry()來獲取文本,您可以將它與布局管理器.grid(row, column)一起使用來創建包含許多Entry()matrix / table 您可以使用兩個for-循環將小部件放入行和列中。

但是您可以在標准 window - tkinter.Tk()中執行此操作 - 而不是在對話框中。

您必須添加從所有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 Examples


順便說一句: PEP 8——Python 代碼的樣式指南

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM