Search code examples
pythonglobal-variables

Please help me with the global variable


So here's my code, I've been following the tutorial from this guy https://www.youtube.com/watch?v=YXPyB4XeYLA&t=13094s @4:35:30

The part where I stuck on is when he talked about using global variable.

Whenever I press update record, it shows me error message

line 80, in update 'first': f_name_editor.get(), NameError: name 'f_name_editor' is not defined

So I went back to check the global variable, it says:

Global variable 'f_name_editor' is undefined at the module level

I am out of ideas already and I still cannot figure it out. I followed all the steps and went back and forth to see if I missed anything during the video and I still can't find the problem

Please help me!

from tkinter import *
import sqlite3

root = Tk()
root.title('Family Member List')
root.geometry('400x400')

conn = sqlite3.connect('Family_list.db')

c = conn.cursor()



'''
c.execute("""CREATE TABLE family(
    first_name text,
    last_name text,
    gender text,
    occupation text
    )
    #""")
'''

#Edit function to update record
def edit():
    editor = Tk()
    editor.title('Update Record')
    editor.geometry('400x400')
    conn = sqlite3.connect('Family_list.db')
    c = conn.cursor()

    record_id = delete_box.get()
    c.execute("SELECT * FROM family WHERE oid =" + record_id)
    records = c.fetchall()

    global f_name_editor
    f_name_editor = Entry(editor,width=30)
    f_name_editor.grid(row=0, column=1, padx=20)
    l_name_editor = Entry(editor,width=30)
    l_name_editor.grid(row=1, column=1, padx=20)
    gender_editor = Entry(editor,width=30)
    gender_editor.grid(row=2, column=1, padx=20)
    occupation_editor = Entry(editor,width=30)
    occupation_editor.grid(row=3, column=1, padx=20)


    f_name_label = Label(editor,text= 'First Name')
    f_name_label.grid(row=0, column =0)
    l_name_label = Label(editor,text= 'Last Name')
    l_name_label.grid(row=1, column =0)
    gender_label = Label(editor,text= 'Gender')
    gender_label.grid(row=2, column =0)
    occupation_label = Label(editor,text= 'Occupation')
    occupation_label.grid(row=3, column =0)

    # LOOP THROUGH RESULT
    for record in records:
        f_name_editor.insert(0, record[0])
        l_name_editor.insert(0, record[1])
        gender_editor.insert(0, record[2])
        occupation_editor.insert(0, record[3])

    #Save Button after edited
    edit_btn = Button(editor, text='Save Record', command = update)
    edit_btn.grid(row=6, column = 1, columnspan = 2, pady=10, padx = 10, ipadx= 100)

def update():
    conn = sqlite3.connect('Family_list.db')
    c = conn.cursor()

    record_id = delete_box.get()
    c.execute('''UPDATE family SET
        first_name=:first,
        last_name=:last,
        gender=:gender,
        occupation=:occupation

        WHERE oid = :oid''',
              {
                  'first': f_name_editor.get(),
                  'last': l_name_editor.get(),
                  'gender': gender_editor.get(),
                  'occupation': occupation_editor.get(),

                  'oid': record_id
              })
    conn.commit()
    conn.close()


def delete():
    conn = sqlite3.connect('Family_list.db')
    c = conn.cursor()
    c.execute("DELETE from family WHERE oid=" + delete_box.get())
    conn.commit()
    conn.close()

def submit():
    conn = sqlite3.connect('Family_list.db')
    c = conn.cursor()
    c.execute("INSERT INTO family VALUES (:f_name,:l_name,:gender,:occupation)",
            {
                'f_name':f_name.get(),
                'l_name':l_name.get(),
                'gender': gender.get(),
                'occupation': occupation.get(),
            })

    conn.commit()
    conn.close()
    f_name.delete(0,END)
    l_name.delete(0,END)
    gender.delete(0,END)
    occupation.delete(0,END)

def query():
    conn = sqlite3.connect('Family_list.db')
    c = conn.cursor()
    c.execute('SELECT *, oid FROM family')
    records = c.fetchall()
    print(records)
    conn.commit()
    conn.close()

    print_records = ''
    for record in records:
        print_records += str(record[0]) + " \t "+ str(record[4]) +'\n'

    query_label = Label(root,text= print_records)
    query_label.grid(row = 8 ,column = 0, columnspan =2 )



f_name = Entry(root,width=30)
f_name.grid(row=0, column=1, padx=20)
l_name = Entry(root,width=30)
l_name.grid(row=1, column=1, padx=20)
gender = Entry(root,width=30)
gender.grid(row=2, column=1, padx=20)
occupation = Entry(root,width=30)
occupation.grid(row=3, column=1, padx=20)
delete_box= Entry(root, width=30)
delete_box.grid(row=9, column = 1)


#create global variable


f_name_label = Label(root,text= 'First Name')
f_name_label.grid(row=0, column =0)
l_name_label = Label(root,text= 'Last Name')
l_name_label.grid(row=1, column =0)
gender_label = Label(root,text= 'Gender')
gender_label.grid(row=2, column =0)
occupation_label = Label(root,text= 'Occupation')
occupation_label.grid(row=3, column =0)
delete_box_label = Label(root, text = 'Select ID Number')
delete_box_label.grid(row=9, column= 0)

#BUTTONS
submit_btn = Button(root,text='Add Record to Database', command= submit)
submit_btn.grid(row = 4, column =0, columnspan=2, pady=10, padx =10, ipadx=100)
query_btn = Button(root, text='Check Submission', command = query)
query_btn.grid(row=5, column = 0, columnspan = 2, pady=10, padx = 10, ipadx= 100)
delete_btn = Button(root, text='Delete Record', command = delete)
delete_btn.grid(row=10, column = 0, columnspan = 2, pady=10, padx = 10, ipadx= 100)

#Update Button
edit_btn = Button(root, text='Update Record', command = update)
edit_btn.grid(row=11, column = 0, columnspan = 2, pady=10, padx = 10, ipadx= 100)


conn.commit()
conn.close()
root.mainloop()

Solution

  • f_name_editor does not exist in global scope until the edit function creates it. The codepath that calls the update function does not pass through the edit function, so the global variable does not exist at that point. You could declare it in global scope, but you'll likely find that just leads to more bugs.