简体   繁体   中英

Updating sqlite3 table with data from tkinter dropdown menu in python

I have two tkinter dropdown menus, created using variables drop_down_var1 and drop_down_var2 , as well as a tkinter text entry box created using the variable id_var .

I want to create an sqlite3 table with an ID key and with data from these dropdown menus. I want the user to be able to insert data through drop_down_var1 , and later on I want the user to be able to update the table through drop_down_var2 and a variable called id_var .

I'm struggling with the syntax for updating the table. I've seen how it's done when your data is from a text entry box but not when the data is from a dropdown menu .

Thanks for any help!

# To create table and insert data from dropdown menu 1 
self.db.execute('CREATE TABLE all_users IF NOT EXISTS' + drop_down_var1.get() + drop_down_var2.get() + '(id INTEGER PRIMARY KEY)')
self.db.execute('INSERT INTO all_users' + drop_down_var1.get())

# To update table with data from dropdown menu 2 
self.db.execute('UPDATE all_users SET drop_down_var2 = ? WHERE id = ?', (drop_down_var2, id_var)) 

It minimal example which shows how to use StringVar to get value from OptionMenu

import tkinter as tk

# --- function ---

def on_click():
    print("value1:", drop_down_var1.get())
    print("value2:", drop_down_var2.get())
    #print(self.db.execute('UPDATE all_users SET drop_down_var2 = ? WHERE id = ?', (drop_down_var2.get(), id_var.get())) 

# --- main ---

master = tk.Tk()

drop_down_var1 = tk.StringVar(master)
drop_down_var1.set("one") # initial value

drop_down_var2 = tk.StringVar(master)
drop_down_var2.set("one") # initial value

drop_down1 = tk.OptionMenu(master, drop_down_var1, "one", "two", "three", "four")
drop_down1.pack()

drop_down2 = tk.OptionMenu(master, drop_down_var2, "one", "two", "three", "four")
drop_down2.pack()

button = tk.Button(master, text="OK", command=on_click)
button.pack()

master.mainloop()

Base on documentation on effbot.org: OptionMenu


BTW: If you append to other string then don't forget to add spaces

see spaces after EXISTS , between arguments and before (id INTEGER PRIMARY KEY)

'CREATE TABLE all_users IF NOT EXISTS ' + drop_down_var1.get() + ' ' drop_down_var2.get() + ' (id INTEGER PRIMARY KEY)'

and after all_users

'INSERT INTO all_users ' + drop_down_var1.get()

Using string formating spaces around {} are better visible

'CREATE TABLE all_users IF NOT EXISTS {} {} (id INTEGER PRIMARY KEY)'.format(drop_down_var1.get(), drop_down_var2.get())

'INSERT INTO all_users {}'.format(drop_down_var1.get())

You can also display string after formatting and test directly in database using tools like DBeaver . Database can give more informatiom if query is incorrect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM