Search code examples
pythonmysqltkintercustomtkinter

Using .get() to pull a barcode from a customtkinter.CTkEntry box


This is part of a much larger project I'm working on, but I'm trying to break it down to the most basic question I could ask. How do I write the following line?

mycursor = mydb.cursor()
UPC_entry = customtkinter.CTkEntry(root, placeholder_text = "Barcode")

search = "SELECT Description FROM doitbest WHERE PrimaryUPC = '%s'" 
mycursor.execute(search, [UPC_entry.get()])
myresult = mycursor.fetchall()
for x in myresult:
        print(x)

select_button = customtkinter.CTkButton(root, text="Search", command=search)

I'm trying to use Python to search my MySQL database by using CustomTkinter as a GUI. Long story short, I want to scan a barcode into a CTkEntry box (UPC_entry), press the CTkButton that I made, have it pull the barcode from the CTkEntry box, and then use that barcode to search my database for the relevant information. No matter how I try to write the above line, I keep getting errors. It all comes down to the last part "UPC_entry.get()". I don't know how to get the barcode out of the CTkEntry box (UPC_entry) and use that to search the database. If I replace UPC_entry.get() with a regular barcode (eg. 077922843671), it will come up with the correct information. I just don't understand what I'm doing wrong. Is .get() even the right thing I should be using? I greatly appreciate any suggestions you guys might have.


Solution

  • command= needs Python function name without () but you put SQL query.

    def my_function():
        #...code...
    
    ...CTkButton(..., command=my_function)  #  <- function's name without ()
    

    When you press button then tkinter gets this function's name and it uses () to execute it. It can't use string as function's name.


    You have to create function which runs SQL and assign this function to button.

    # --- functions ---
    
    def my_function():
        search = "SELECT Description FROM doitbest WHERE PrimaryUPC = '%s'" 
        mycursor.execute(search, [UPC_entry.get()])
        myresult = mycursor.fetchall()
        for x in myresult:
                print(x)
    
    # --- main ---
    
    mycursor = mydb.cursor()
    UPC_entry = customtkinter.CTkEntry(root, placeholder_text = "Barcode")
    
    select_button = customtkinter.CTkButton(root, text="Search", command=my_function)  #  <- function's name without ()
    

    BTW: this function's name without () is called callback (not only in Python but also in other languages - ie. in JavaScript)