我正在尝试使用tkinter在Python中创建一个输入表。输入表具有可以更改的初始值。当输入已被编辑时,我想保存更改。我使用TinyDB作为数据库来存储输入值。
有人可以举例说明如何做到这一点吗?
答案 0 :(得分:0)
虽然我同意Bryan的观点,但可以在下面找到使用tkinter
存储多个输入的快速示例:
from tkinter import *
root = Tk()
entry = []
def command(entry):
output = []
for i in range(len(entry)):
output.append(entry[i].get())
print(output)
for i in range(10):
entry.append(Entry(root))
entry[i].pack()
Button(root, text="Ok", command=lambda:command(entry)).pack()
root.mainloop()
这会创建10个entry
元素,并使用button
触发的命令将所有元素存储在list
中。
答案 1 :(得分:0)
我发现由于没有显示我的初始代码,我收到了很多关键响应。我想我在输入这个简单的例子时找到了解决方案,它似乎工作正常。但是必须使它面向对象。
from tkinter import *
from tinydb import TinyDB, Query
# Name on database with stored parameter values (confined and free parameters)
param_db_name = 'db5.json'
db2 = TinyDB(param_db_name)
# Get field name and values for free parameters in Model1:
model_name = 'Model1'
felt = Query()
fields = (db2.search(felt.Model_name == model_name)[0]['free_par']).keys()
fields_val = (db2.search(felt.Model_name == model_name)[0]['free_par']).values()
#print('Fields_val: ',fields_val)
def save_params(entries, fields):
res_dict = {}
for field in fields:
res_dict[field] = float(entries[field].get())
print('Res dict:', res_dict)
felt = Query()
db2.update({'free_par': res_dict}, felt.Model_name == model_name)
def makeform(root, fields,ff):
entries = {}
i = 0
for field in fields:
row = Frame(root)
lab = Label(row, width=32, text=field+": ", anchor='w')
ent = Entry(row)
ent.insert(0, [ff[i]])
row.pack(side=TOP, fill=X, padx=5, pady=5)
lab.pack(side=LEFT)
ent.pack(side=RIGHT, expand=YES, fill=X)
entries[field] = ent
i=i+1
return entries
if __name__ == '__main__':
root = Tk()
root.wm_title("Model parameters")
ents = makeform(root, fields, list(fields_val))
b1 = Button(root, text='Lagre',command=lambda: save_params(ents,fields))
b1.pack(side=LEFT, padx=5, pady=5)
b2 = Button(root, text='Avslutt', command=root.quit)
b2.pack(side=RIGHT, padx=5, pady=5)
root.mainloop()
[{'Model_name': 'Model1','con_par': {'CPar1': 1, 'CPar2': 2, 'CPar3': 3.0},'free_par': {'FPar1': 0.589, 'FPar2': 1.44, 'FPar3': 3.0, 'FPar4': 2.427}},
{'Model_name': 'Model2','con_par': {'CPar1': 11, 'CPar2': 12, 'CPar3': 13.0},'free_par': {'FPar1': 10.589,'FPar2': 11.44,'FPar3': 13.0,'FPar4': 12.427}}]