我尝试使用TK搜索如何从输入中保存变量,但我无法找到任何方法。
这是我使用的代码的清洁版本:
from tkinter import *
from tkinter import ttk
main=Tk()
main.title("Test")
book = []
class test1:
def __init__(self):
self.name = ""
self.tel = ""
new1 = test1()
def salva(argm):
argm.name = str(nome.get())
argm.tel = str(telefono.get())
def nuovo_ordine():
tutto = Toplevel()
scheda = ttk.Frame(tutto,padding="10 10 10 10")
scheda.rowconfigure(0, weight=1)
scheda.columnconfigure(0, weight=1)
scheda.grid(column=0,row=0,sticky=(N,W,E,S))
global nome
global telefono
global new1
nome = StringVar()
telefono = StringVar()
ttk.Label(scheda,text="Telefono").grid(column=1,row=2)
ttk.Label(scheda,text="Nome").grid(column=1,row=1)
tel1 = ttk.Entry(scheda,textvariable=telefono).grid(column=2,row=2)
nome1 = ttk.Entry(scheda,textvariable=nome).grid(column=2,row=1)
salva_tasto=Button(scheda,text="Salva",command=salva(new1)).grid(column=1,row=4)
fine_tasto=Button(scheda,text="Fine",command=tutto.destroy).grid(column=3,row=4)
def stampa(argm2):
print (argm2.name)
print (argm2.tel)
dentro = ttk.Frame(main,padding="10 10 10 10")
dentro.rowconfigure(0, weight=1)
dentro.columnconfigure(0, weight=1)
dentro.grid(column=0,row=0,sticky=(N,W,E,S))
nuovo=Button(dentro,text="Aggiungi Ordine", command=nuovo_ordine, width=16).grid(column=1,row=2)
stampa=Button(dentro,text="Stampa Ordini",command=stampa(new1), width=16).grid(column=2,row=3)
chiudi=Button(dentro,text="Chiudi",command=main.destroy, width=16).grid(column=3,row=4)
main.mainloop()
问题是,似乎它无法在变量中存储输入,而如果我尝试: print(telefono.get()) 我得到了正确的价值......
提前致谢!
答案 0 :(得分:3)
salva_tasto=Button(scheda,text="Salva",command=salva(new1)).grid(column=1,row=4)
如果在command
中指定函数的参数,则必须将其包装在lambda中,以便不立即调用它。
salva_tasto=Button(scheda,text="Salva",command= lambda *args: salva(new1)).grid(column=1,row=4)
顺便说一句,尝试将小部件分配给变量并在同一行上grid
或pack
是一个常见的错误。如果您希望salva_tasto
成为按钮,而不是grid
返回的任何内容,则应该
salva_tasto=Button(scheda,text="Salva",command= lambda *args: salva(new1))
salva_tasto.grid(column=1,row=4)
编辑:您还有一个命名问题。您有一个函数stampa
,但是您使用stampa=Button(...
覆盖了该名称。您应该将其中一个变量的名称更改为其他变量。