python让用户输入矩阵_python-GUI(输入和输出矩阵)?

使用tkinter,您不需要特殊的表格小部件即可执行此操作,只需创建一个普通条目小部件的网格即可.如果有太多需要滚动条的地方,它会稍微困难一些(此站点上有一些示例,说明如何做到这一点),但是仅创建一个很小的网格就非常简单了.

这是一个示例,其中还包括一些输入验证:

import tkinter as tk

class SimpleTableInput(tk.Frame):

def __init__(self, parent, rows, columns):

tk.Frame.__init__(self, parent)

self._entry = {}

self.rows = rows

self.columns = columns

# register a command to use for validation

vcmd = (self.register(self._validate), "%P")

# create the table of widgets

for row in range(self.rows):

for column in range(self.columns):

index = (row, column)

e = tk.Entry(self, validate="key", validatecommand=vcmd)

e.grid(row=row, column=column, stick="nsew")

self._entry[index] = e

# adjust column weights so they all expand equally

for column in range(self.columns):

self.grid_columnconfigure(column, weight=1)

# designate a final, empty row to fill up any extra space

self.grid_rowconfigure(rows, weight=1)

def get(self):

'''Return a list of lists, containing the data in the table'''

result = []

for row in range(self.rows):

current_row = []

for column in range(self.columns):

index = (row, column)

current_row.append(self._entry[index].get())

result.append(current_row)

return result

def _validate(self, P):

'''Perform input validation.

Allow only an empty value, or a value that can be converted to a float

'''

if P.strip() == "":

return True

try:

f = float(P)

except ValueError:

self.bell()

return False

return True

class Example(tk.Frame):

def __init__(self, parent):

tk.Frame.__init__(self, parent)

self.table = SimpleTableInput(self, 3, 4)

self.submit = tk.Button(self, text="Submit", command=self.on_submit)

self.table.pack(side="top", fill="both", expand=True)

self.submit.pack(side="bottom")

def on_submit(self):

print(self.table.get())

root = tk.Tk()

Example(root).pack(side="top", fill="both", expand=True)

root.mainloop()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值