![](/img/trans.png)
[英]How do I populate tkinter drop-down box with data retrieved from my SQLite database?
[英]Inserting data from an OptionMenu() drop-down menu into an SQLite database in Python
我正在用 python 制作帶有下拉菜單的 GUI(來自 tkinter 的 OptionMenu)。
我想將下拉菜單中的數據插入SQLite 數據庫,例如,有一個用於選擇您的汽車的下拉菜單,我想將用戶的汽車選擇連同條目日期一起插入數據庫。
我一直在檢查如何在 python 中使用帶有 sqlite 的tkinter 和在 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.