0

我有一个 Tkinter 应用程序,并且在该应用程序内我有一个OptionMenu它给了我id's位于列表中的所有内容vehicleid。请注意,此列表可以变大或变小。

现在我希望我的按钮根据用户的选择将数据发送到数据库ownervehicleid因此,如果我有例如 2 vehicleid's,我首先需要选择一个特定的vehicleid,并且对于每个vehicleid我需要选择一个特定的owner.

因此,如果是 2,vehicleid我的数据库应如下所示:

vehicleid        owner
C161      ---    Spain
C162      ---    United Kingdom

应用看起来像这样:

在此处输入图像描述

这是我的代码:

owner = ['Spain', 'United Kingdom', 'Malaysia']
vehicleid = ['C161', 'C162']

window = Tk()
window.title("Running Python Script") # Create window
window.geometry('550x300') # Geo of the window

##These are the option menus
dd_owner = StringVar(window)
dd_owner.set(owner[0]) # the first value
w = OptionMenu(window, dd_owner, *owner)
w.grid(row=1, column=1)

dd_id = StringVar(window)
dd_id.set(vehicleid[0])
w0 = OptionMenu(window, dd_id, *vehicleid)
w0.grid(row=0, column=1)

##The run button 
run_list_button =Button(window, text="Send data of ID's to database!")
run_list_button.grid(column=0, row=3)

##These are the titles
l1 = Label(window, text='Select Owner', width=15)
l1.grid(row=1, column=0)

l0 = Label(window, text='Select vehicle id:', width = 30)
l0.grid(row=0, column=0)

mainloop()
4

2 回答 2

1

尽管您的问题令人困惑。在查看您的讨论后,我了解到您希望仅在用户确认他们的选择后将所有数据发送到数据库。

在这种情况下,您可能需要一个字典来存储车辆 ID 和所有者{"vehicle_id": [], "owner": []},直到用户单击更新数据库按钮。更新数据库后,请确保清空字典,以便以前选择的项目不会再次插入数据库。

注意:您仍然需要多次按下另一个按钮才能将数据插入字典。您可以使用控制变量的跟踪方法选择不拥有按钮

这是一个例子

from tkinter import *
import sqlite3


CREATE_QUERY = "CREATE TABLE IF NOT EXISTS vehicle(vehicle_id VARCHAR(5), owner VARCHAR(100));"
INSERT_QUERY = "INSERT INTO vehicle(vehicle_id, owner) VALUES(?, ?);"
SELECT_QUERY = "SELECT * FROM vehicle;"

sql_file = "sample.db"

id_dict = {"vehicle_id": [], "owner": []}

def create_data_base():

     with sqlite3.connect(sql_file) as conn:
         conn.execute(CREATE_QUERY)
         conn.commit()

def insert_to_db():
    global id_dict
    with sqlite3.connect(sql_file) as conn:

        for value in zip(*id_dict.values()):
    
            conn.execute(INSERT_QUERY, value)

        conn.commit()
    
    id_dict = {"vehicle_id": [], "owner": []}  # empty the list once you insert the data
    display_data()
    
def display_data():
    with sqlite3.connect(sql_file) as conn:
        curr = conn.cursor()
        curr.execute(SELECT_QUERY)
        items = curr.fetchall()

    print(items)


def add():

    id_dict["vehicle_id"].append(dd_id.get())
    id_dict["owner"].append(dd_owner.get())
    print(id_dict)


owner = ['Spain', 'United Kingdom', 'Malaysia']
vehicleid = ['C161', 'C162']

window = Tk()
window.title("Running Python Script") # Create window
window.geometry('550x300') # Geo of the window


create_data_base()

##These are the option menus
dd_owner = StringVar(window)
dd_owner.set(owner[0]) # the first value
w = OptionMenu(window, dd_owner, *owner)
w.grid(row=1, column=1)

dd_id = StringVar(window)
dd_id.set(vehicleid[0])
w0 = OptionMenu(window, dd_id, *vehicleid)
w0.grid(row=0, column=1)


Button(window, text='Add', command=add).grid(column=1, row=3)

##The run button 
run_list_button =Button(window, text="Send data of ID's to database!", command=insert_to_db)
run_list_button.grid(column=0, row=3)

##These are the titles
l1 = Label(window, text='Select Owner', width=15)
l1.grid(row=1, column=0)

l0 = Label(window, text='Select vehicle id:', width = 30)
l0.grid(row=0, column=0)

window.mainloop()

上面的代码会将字典中的所有数据插入到数据库中。

于 2021-06-01T13:02:25.653 回答
1

首先,您应该将数据存储在某处(字典或文件..),然后在用户按下按钮时读取数据。

import mysql.connector as mysql
....

mydb = mysql.connect(host = 'localhost',user = 'root',passwd = '****.',database = 'table_data')

data = {}
def store():
    if dd_id.get() not in data:
        data[dd_id.get()] = dd_owner.get()
    print(data)

def upload():
    cur = mydb.cursor()
    for item in data.items():
        sql = 'INSERT INTO table_data VALUES (%s,%s)'
        params = (item[0],item[1])

        cur.execute(sql,params)
        mydb.commit()
    
    print('Done')

....
# The store button
Button(window, text="Store data!",command=store).grid(column=0, row=3)

# The database button
Button(window, text="Send to database",command=upload).grid(column=0, row=4)

这将在单击相应按钮时将数据存储在数据库中,并且不允许重复条目或更新条目。

于 2021-06-01T13:33:18.020 回答