python - 在 Python 中将 OptionMenu() 下拉菜单中的数据插入 SQLite 数据库
问题描述
我正在用python中的下拉菜单(来自tkinter的OptionMenu)制作一个GUI。
我想将下拉菜单中的数据插入SQLite 数据库,例如,有一个用于选择汽车的下拉菜单,我想将用户的汽车选择连同输入日期一起插入数据库。
我一直在检查如何在 python 中使用 tkinter 和 sqlite并在 Python中使用 OptionMenu,但我无法让我的代码工作(请参阅错误消息)。
我正在使用 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
解决方案
你这个我做了一些改变。
import tkinter as tk
import sqlite3 as sq
import datetime
# Connection to SQLite
con = sq.connect('Cars.db')
# Car choice dictionary for drop-down menu
carD = ['BMW', 'Volvo', 'Mitsubishi']
root = tk.Tk()
canvas = tk.Canvas(root, height=500, width= 500, bg="white")
canvas.pack()
carV = tk.StringVar(root)
carV.set('Choose your car')
carDDM = tk.OptionMenu(canvas, carV, *carD)
carDDM.pack()
# Function for inserting car choice from drop-down menu into SQLite
def SaveCarChoice():
c = con.cursor()
c.execute('CREATE TABLE IF NOT EXISTS CAR (sql_date VARCHAR(20), sql_carV VARCHAR(20) NOT NULL)')
today = str(datetime.date.today())
today = today[8:] + '-' + today[5:7] + '-' + today[:4]
c.execute('INSERT INTO CAR (sql_date, sql_carV) VALUES (?, ?)', (today, carV.get()))
con.commit()
# Button for user to activate the function inserting data into SQLite
carB = tk.Button(canvas, text="Enter", command=SaveCarChoice)
carB.pack()
root.mainloop()
推荐阅读
- javascript - 当我将 eventHandler 或 onClick 添加到元素时,“它在哪里”?
- java - 如何将类存储在 Array/Arraylists/Lists 中?
- html - 在不影响页脚的情况下让一个部分占据全屏
- c# - 使用索引更改 ObservableCollection 中对象的属性
- java - 使用 corePoolSize 而不是 maxPoolSize 的 InvokeAll 方法
- swift - 如何取消延迟的线程?
- java - 这是一个意外错误。请提交包含 idea.log 文件的错误
- c# - CS0426 错误在 switch 块中抛出,但不在 if 语句中,如何修复?
- python-3.x - 将python连接到命令提示符
- c - 由 fscanf 引起的 fscanf 的 Profiler 错误