试图让tkinter应用程序将数据保存到SQLite3数据库中
我正在编写一个小程序来简单地保存文本数据和整数数据 进入试图让tkinter应用程序将数据保存到SQLite3数据库中,sqlite,tkinter,python-3.3,Sqlite,Tkinter,Python 3.3,我正在编写一个小程序来简单地保存文本数据和整数数据 进入SQLite3数据库 我用以下代码创建了名为test.db的数据库: con = sqlite3.connect('test.db') cur = con.cursor() cur.execute('drop table if exists data') cur.execute('create table data(t1 TEXT, i1 INT)') con.commit() print('DB created') 问题是当我运行它时,
SQLite3
数据库
我用以下代码创建了名为test.db
的数据库:
con = sqlite3.connect('test.db')
cur = con.cursor()
cur.execute('drop table if exists data')
cur.execute('create table data(t1 TEXT, i1 INT)')
con.commit()
print('DB created')
问题是当我运行它时,它会告诉我
告诉我,cur.execute
行需要字符串作为参数,但我已经将text1
定义为带有StringVar
的字符串
from tkinter import *
from tkinter import ttk
import sqlite3
def savedata(text1, int1):
con = sqlite3.connect('test.db')
cur = con.cursor()
cur.execute(('INSERT INTO data (t1, i1) VALUES (?,?)', (text1, int1)))
con.commit()
print('record inserted in data')
root = Tk()
root.title("Little Program To Save Data")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column = 0, row = 0, sticky = (N,W,E,S))
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
text1 = StringVar()
text_entry = ttk.Entry(mainframe, width = 20, textvariable=text1)
text_entry.grid(column = 2, row = 1, sticky = (N,W,E,S))
int1 = IntVar()
int_entry = ttk.Entry(mainframe, width = 20, textvariable=int1)
int_entry.grid(column = 2, row = 2, sticky = (N,W,E,S))
ttk.Button(mainframe, text = "Save!", command=savedata(text1, int1)).grid(column = 3, row = 3, sticky = (W, E))
for child in mainframe.winfo_children():
child.grid_configure(padx = 5, pady = 5)
root.mainloop()
代码不起作用,因为
StringVar
和IntVar
不是典型的Python对象str
和int
,它们实际上表示Tcl变量,您可能会将这些变量设置为包含可以分类为字符串或整数的值
您需要做的第一件事是将savedata(text1,int1)
更改为savedata(text1.get(),int1.get())
,以便实际获取存储在其中的值。其次,您在按钮
小部件中定义命令
参数值的方式是错误的,因为您是在执行它,而不是在实际单击按钮时传递要执行的函数。通过将该部分更改为command=lambda:savedata(…)
,可以解决这个问题。第三,你在打电话
cur.execute(('INSERT INTO data (t1, i1) VALUES (?,?)', (text1, int1)))
但这肯定会失败,因为您正在将一个元组传递给execute
,实际需要的是:
cur.execute('INSERT INTO data (t1, i1) VALUES (?,?)', (text1, int1))
现在您的代码可以工作了,但是这里不需要使用Tcl变量。谢谢!!mmgp,很好的解释和演示。再次,mmgp,还有一个问题。