Skip to content
Advertisement

How can i use value of a combobox in another external file to help cursor.excute to search in database? NameError: name ‘combo1’ is not defined

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

Advertisement

Answer

You’ll want to modify function_ext to accept combo1 as a parameter like so

def function_ext(combobox):  # add the parameter
    #recover value
    con = sqlite3.connect('/home/jack/Desktop/database.db')
    cursor = con.cursor()
    # use the 'combobox' param here and .get() the value (thanks acw1668)
    cursor.execute("SELECT x FROM Table1 WHERE element = ?", (combobox.get(),))
    select = cursor.fetchone()

Then in your Main.py file you need to import function_ext

from B.py import function_ext

then you can call function_ext from Main.py

...
combo1=ttk.Combobox(window, width = 22)
combo1['value'] =["Item 1", "Item 2", "Item 3"]
combo1.place(x=10, y=10)
combo1.set("Select")
...
function_ext(combo1)  # call the function using 'combo1' as the parameter

For what it’s worth, the NameError you’ve been getting is caused because your B.py file has no idea that your Main.py file exists, and therefore has no idea what combo1 is. Essentially, there’s nothing in B.py named combo1, so you can’t refer to anything with that name without getting an error.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement