Python 将输入小部件中的输入写入CSV(tkinter)
我想要的是一个简单的小部件,它将条目中输入的值与日期和时间一起添加到cvs文件中,如下所示:Python 将输入小部件中的输入写入CSV(tkinter),python,python-3.x,tkinter,Python,Python 3.x,Tkinter,我想要的是一个简单的小部件,它将条目中输入的值与日期和时间一起添加到cvs文件中,如下所示: 2016-02-22 11:40 12 2016-02-22 11:43 549 2016-02-22 11:44 321 到目前为止,我的代码是: from tkinter import * import csv import datetime def enter_button(): now = datetime.datetime.now() amount =
2016-02-22 11:40 12
2016-02-22 11:43 549
2016-02-22 11:44 321
到目前为止,我的代码是:
from tkinter import *
import csv
import datetime
def enter_button():
now = datetime.datetime.now()
amount = e1.get()# That is where I thought I should get the Input from the widget
with open('File.csv', 'a') as f:
w = csv.writer(f,dialect='excel-tab')
w.writerow([now.strftime("%Y-%m-%d %H:%M"), amount]) # write Date/Time and the value
f.close()
master = Tk()
e1 = Entry(master)
Label(master, text='Enter Number Here').grid(row=0)
myButton=Button(master,text='Enter',command=enter_button())
e1.grid(row=0,column=1)
myButton.grid(row=1,column=0)
mainloop()
代码运行,小部件如下所示:
问题是输入字段中的值没有写入cvs文件。。。。我只得到按下按钮(myButton
)的日期和时间。。。。
这些将写入.csv
文件。
那么,从输入字段中获取函数值(enter_按钮
)时,我错过了什么呢?
谢谢原因是您正在调用
输入按钮
功能
myButton = Button(master, text='Enter',command=enter_button())
^^^
您需要为命令
选项指定函数名
myButton = Button(master, text='Enter', command=enter_button)
另外,您不需要调用f.close()
,因为with
语句会为您处理这些问题