【问题标题】:How to trigger a run button based on all the values in a list?如何根据列表中的所有值触发运行按钮?
【发布时间】:2021-06-01 11:01:34
【问题描述】:

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

现在我希望我的按钮根据用户的选择将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()

【问题讨论】:

  • 您是在询问如何将数据发送到数据库的代码。
  • 将数据发送到数据库的代码并不难。但我希望一次发送所有数据。所以取决于我在vehicleid中有多少物品@
  • @Sujay 就是这样。
  • 一次性?一份一份寄出去。您一次只能选择一组值。
  • 实际上,当您尝试一次发送所有数据时遇到了什么问题?

标签: python list tkinter button tkinter.optionmenu


【解决方案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)

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

【讨论】:

    【解决方案2】:

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

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

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

    这是一个例子

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

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

    【讨论】:

    • 为什么不{'id1':'owner1'}
    • @CoolCloud 在哪里?
    • 你以{"vehicle_id": [], "owner": []}格式存储数据,为什么不把id作为key,因为它是唯一的
    • @CoolCloud 我不认为 id 是唯一的 OP 程序,因为他为用户提供了从给定列表中选择的选项,OP 不检查 id 的唯一性。我像这样存储数据{"vehicle_id": [], "owner": []},因为他似乎想一次将所有数据发送到数据库。如果我使用类似{'id1':'owner1'} 的东西,写入新数据时该值将被删除。
    • 是的,这就是所谓的更新 id。只是一个建议,你可以忽略它
    猜你喜欢
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    相关资源
    最近更新 更多