I'm having trouble using the combobox in an external file. Basically the combobox is in the main file and I would like to use its selected value in the external file. If I select a certain item, it should help cursor.excute
to search for a database table, so cursor.execute("SELECT x FROM Table1 WHERE element = ?", (combo1,))
As you can see, the combobox combo1
is present in the main file and is not detected by the B.py file where cursor.excute is located. I get the error:
cursor.execute("SELECT x FROM Table1 WHERE element = ?", (combo1,))
NameError: name 'combo1' is not defined
How can I solve the problem? Can you show me the code? I'm new to Python
Main file
from tkinter import ttk
import tkinter as tk
from tkinter import *
import sqlite3
from two import *
window = tk.Tk()
window.geometry("350x200")
style = ttk.Style(window)
combo1=ttk.Combobox(window, width = 22)
combo1['value'] =["Item 1", "Item 2", "Item 3"]
combo1.place(x=10, y=10)
combo1.set("Select")
btn = Button(window, text="Click")
btn.place(x=10, y=80)
B.py
import sqlite3
def function_ext():
#recover value
con = sqlite3.connect('/home/jack/Desktop/database.db')
cursor = con.cursor()
cursor.execute("SELECT x FROM Table1 WHERE element = ?", (combo1,))
select = cursor.fetchone()
import tkinter as tk
andfrom tkinter import *
(and realistically, you shouldn't do this). It's best to just useimport tkinter as tk
and then access tk widgets liketk.Button
,tk.Entry
, etc. Star imports are usually a bad ideaButton
only works if you dofrom tkinter import *
. Whereastk.Button
works because ofimport tkinter as tk
(the "as tk" part is where thetk.
namespace prefix comes from). The problem with star imports is that if any other module you're importing also has a class calledButton
-for example-, the interpreter won't know whichButton
you're referring to (tkinter or some other module), so it's best to namespace things appropriately.