Python 如何基于列表中的所有值触发运行按钮?

Python 如何基于列表中的所有值触发运行按钮?,python,list,tkinter,button,tkinter.optionmenu,Python,List,Tkinter,Button,Tkinter.optionmenu,我有一个Tkinter应用程序,在该应用程序中我有一个选项菜单,它为我提供了列表车辆id中的所有id。请注意,此列表可以变大或变小 现在,我希望我的按钮根据用户的选择将owner和vehicleid的数据发送到数据库。因此,如果我有例如2个vehicleid的,我首先需要选择一个特定的vehicleid,对于每个vehicleid,我需要选择一个特定的所有者 因此,在2vehicleid的情况下,我的数据库应该如下所示: vehicleid owner C161 ---

我有一个Tkinter应用程序,在该应用程序中我有一个
选项菜单
,它为我提供了列表
车辆id
中的所有
id。请注意,此列表可以变大或变小

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

因此,在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()

这是我的代码:

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()

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

在这种情况下,您可能需要一个字典来存储车辆id和车主
{“车辆id”:[],“车主”:[]}
,直到用户单击更新数据库按钮。更新数据库后,请确保清空字典,以便不再将以前选择的项插入数据库

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

这里有一个例子

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()

上述代码将把字典中的所有数据插入数据库。

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

在这种情况下,您可能需要一个字典来存储车辆id和车主
{“车辆id”:[],“车主”:[]}
,直到用户单击更新数据库按钮。更新数据库后,请确保清空字典,以便不再将以前选择的项插入数据库

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

这里有一个例子

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()

上述代码将把字典中的所有数据插入数据库。

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

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)

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

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

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)


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

您是否询问如何向数据库发送数据的代码。向数据库发送数据的代码并不难。但是我希望数据一次发送出去。因此,根据我在
vehicleid
@Sujay中的物品数量,情况就是这样。一次完成?逐一发送。您一次只能选择一组值。实际上,当您试图一次发送所有数据时,您遇到了什么问题?您是在询问如何将数据发送到数据库的代码。将数据发送到数据库的代码并不难。但是我希望数据一次发送出去。因此,根据我在
vehicleid
@Sujay中的物品数量,情况就是这样。一次完成?逐一发送。您一次只能选择一组值。实际上,当您试图一次发送所有数据时,您遇到了什么问题?为什么不
{'id1':'owner1'}
?@CoolCloud where?您以
{“vehicle_id:[],“owner:[]}
的格式存储数据,为什么不将id作为密钥,因为它是unique@CoolCloud我不认为id是唯一的OP程序,因为他为用户提供了从给定列表中选择的选项,OP不会检查id的唯一性。我存储数据
{“vehicle_id:[],“owner:[]}
像这样,因为他似乎想一次将所有数据发送到数据库。如果我使用类似这样的
{'id1':'owner1'}
值将在写入新数据时被删除。是的,这称为更新id。这只是一个建议,您可以忽略它为什么不
{'id1':'owner1'}
?@CoolCloud where?您以
{vehicle\u id:[],“owner:[]}
格式存储数据,为什么不将id作为密钥,因为它是unique@CoolCloud我不认为id是唯一的OP程序,因为他为用户提供了从给定列表中选择的选项,OP不会检查id的唯一性。我存储数据
{“vehicle_id:[],“owner:[]}
像这样,因为他似乎想一次将所有数据发送到数据库。如果我使用了类似这样的
{'id1':'owner1'}
值将在写入新数据时被删除。是的,这称为更新id。这只是一个建议,您可以忽略它