【发布时间】:2019-11-27 15:07:47
【问题描述】:
我正在 python 中使用 下拉菜单(来自 tkinter 的 OptionMenu)制作一个 GUI。
我想将下拉菜单中的数据插入 SQLite 数据库,例如,有一个用于选择汽车的下拉菜单,我想将用户的汽车选择插入数据库连同条目的日期。
我一直在检查 how to use tkinter with sqlite in python 和 Use OptionMenu in Python,但我的代码无法正常工作(请参阅错误消息)。
我使用的是 Python 3.7.4,Windows 10。
谢谢!
from tkinter import *
import sqlite3 as sq
import datetime
# Main window
window = Tk()
# Connection to SQLite
con = sq.connect('Cars.db')
# Car choice variable and placeholder
carV = StringVar(window)
carV.set('Choose your car')
# Car choice dictionary for drop-down menu
carD = {'BMW', 'Volvo', 'Mitsubishi'}
# Car chhoice drop-down menu
carDDM = OptionMenu(window, carV, carD)
carDDM.place(x=150,y=150)
# Function for inserting car choice from drop-down menu into SQLite
def SaveCarChoice():
c.execute('CREATE TABLE IF NOT EXISTS (sql_date TEXT, sql_carV INTEGER)')
date = datetime.date(int(year.get()),int(month.get()), int(day.get()))
c.execute('INSERT INTO (sql_date, sql_carV) VALUES (?, ?)', (date, carDDM.get())
con.commit()
# Button for user to activate the function inserting data into SQLite
carB = Button(window, text="Enter",command=SaveCarChoice())
carB.pack()
window.mainloop()
# ERROR MESSAGE
File "<ipython-input-5-7b7f66e12fbf>", line 42
con.commit()
^
SyntaxError: invalid syntax
【问题讨论】:
-
您在前一行缺少一个结束
),即 `c.execute(.... And thiscarDDM.get()` 应该读取carV.get()variable=fromOptionMenu
标签: python sqlite tkinter optionmenu