I am trying to fetch a phone number from a database and input it into an Tkinter entry field

  python, tkinter

I have a database already built, and I am trying to have the user input the first and last name on the GUI and then it would return the phone number associated with it. However, I cannot get the phone number to be shown in the read-only entry field. Below is the code:

import tkinter as tk
from tkinter import *
from tkinter import messagebox

#Define window
root = tk.Tk()
root.title("tk")

# Make labels
fName = Label(root, text="First Name").grid(row=0, column=0)
lName = Label(root, text="Last Name").grid(row=0, column=2)
Phone = Label(root, text="Phone Number -->").grid(row=1, column=2)

# Make entry fields
fNameStr = StringVar()
lNameStr = StringVar()

e1 = Entry(root, textvariable=fNameStr, width=20).grid(row=0, column=1)
e2 = Entry(root, textvariable=lNameStr,width=20).grid(row=0, column=3)
e3 = Entry(root, width=20, state=DISABLED).grid(row=1, column=3)


def findContact():
    import sqlite3
    conn = sqlite3.connect('ContactsDB3.db')
    c = conn.cursor()

    # ensure fName is a string
    fName = fNameStr.get()
    str_fName = str(fName)
    if not str_fName.isalpha():
        messagebox.showerror("ERROR", "ERROR. First name must be a string")
        raise Exception("ERROR. First name must be a string.")

    # ensure lName is a string
    lName = lNameStr.get()
    str_lName = str(lName)
    if not str_lName.isalpha():
        messagebox.showerror("ERROR", "ERROR. Last name must be a string")
        raise Exception("ERROR. Last name must be a string.")
    
    sql = ("SELECT PhoneNumber FROM Contacts WHERE FirstName = ? AND LastName = ?")
    c.execute(sql, (str_fName, str_lName))
    result = c.fetchone()
    e3.insert(END, result)
    
# Create and insert Submit button
Button(root, text="Submit", command=findContact).grid(row=1, column=0)


root.mainloop()

I inserted a print statement earlier to see if the code was even capable of fetching the phone number, and it gave me the correct result; the problem seems to arise when I try to insert the result into the entry field. I am given the error:

Exception in Tkinter callback Traceback (most recent call last):
File
"C:UsershakthAppDataLocalProgramsPythonPython39libtkinter_init_.py",
line 1892, in call
return self.func(*args) File "C:UsershakthDesktopPython_II_2021Assignment5Assignment_5.py",
line 45, in findContact
e3.insert(END, result) AttributeError: ‘NoneType’ object has no attribute ‘insert’

So e3.insert(END, result) has an attribute error and I do not understand how to alleviate the issue. I was thinking that the result value needed to be changed to an actual string so that I could insert it, but wouldn’t the "result" already be a string if it’s taken from the database where the column is a VARCHAR? I just need some direction here, thank you.

Source: Python Questions

LEAVE A COMMENT