更正脚本中的属性 and/or UnboundLocalError

Correcting Attribute and/or UnboundLocalError in script

此脚本接受用户输入(针对员工)并通过 SQLAlchemy 添加到 sqlite3 .db。它工作正常,直到我在年龄字段的 add_data 方法中添加 try: except 子句(计划向其他字段添加更多 try/except 子句)。年龄字段需要是用户选择的整数。我意识到我需要一种方法来捕获由于用户向字段中添加字符串而不是数字而导致的任何错误。相关代码。 . .

try:
        self.age = self.age_var.get()
    except ValueError:
        showinfo("Error:", "Please Enter A Number In Age Field.")

然而,当我这样做时,它会产生一个问题,因为 age 现在变成了一个局部变量(正如 Backtrack 在另一个 post 中指出的那样)并且我得到了 UnboundLocalError: local variable 'age' 在赋值前引用。我尝试通过分离数据检索和添加到数据库来更改代码,就像这样。 . .

def get_data(self):        
    self.name = self.name_var.get()
    try:
        self.age = self.age_var.get()
    except ValueError:
        showinfo("Error:", "Please Enter A Number In Age Field.")
    self.addr = self.address_var.get()
    self.city = self.city_var.get()
    self.state = self.state_var.get()
    self.zip = self.zip_var.get()   
    self.ssn = self.ssn_var.get()
    self.phone = self.phone_var.get()
    self.cell = self.cell_var.get()

def add_data(self):
    self.get_data()
    # create new Employee in .db
    new_person = Employee(name=self.name, age=self.age, address=self.addr, city=self.city, state=self.state, zip=self.zip, ssn=self.ssn, phone=self.phone, cell=self.cell)
    session.add(new_person)
    session.commit()
    session.close()
    self.callback()
    return

但是,我有不同形式的相同问题。现在我得到 AttributeError: GUI instance has no attribute 'age'。我不确定如何解决这些问题。我尝试在 try/except 子句 self.age=0 之前为 age 添加一个默认值,这确实纠正了错误,但又产生了另一个问题。 .如果用户输入的是字符串而不是 int,showinfo 框会出现警告,但是当用户单击 'ok' 时,默认值“0”会自动添加到数据库中,而不是再给用户一次机会输入年龄的数字。当然,我可以将年龄字段更改为 Class Employee 中的字符串,但这不是我想要的。我不知道该怎么办。任何帮助是极大的赞赏!无论如何,这是原始代码。 . .

from datetime import datetime
from Tkinter import *
from tkMessageBox import *
import sqlite3, sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, DateTime, Integer, String, MetaData
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# map classes to tables through Base Class
Base = declarative_base()


class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String(250))
    age = Column(Integer)
    address = Column(String(250))
    city = Column(String(10))
    state = Column(String(2))
    zip = Column(Integer)
    ssn = Column(String(12))
    phone = Column(String(12))
    cell = Column(String(12))

# create engine for Session connection
engine = create_engine('sqlite:///employee.db')

# create all tables in engine ('CREATE TABLE' in raw SQL)
Base.metadata.create_all(engine)

# create configured 'Session' class
Session = sessionmaker(bind=engine)

# create session
session = Session()


class GUI:
    def __init__(self, parent):
        self.parent = parent

        # create top frame
        frame = Frame(parent)
        frame.pack(expand=YES, fill=BOTH, padx=5, pady=5)

        # create bottom frame
        btm_frame = Frame(parent, relief=SUNKEN, borderwidth=1)
        btm_frame.pack(side=BOTTOM, expand=YES, fill=BOTH, padx=5, pady=5)

        # create datetime object
        d = datetime.today()
        date = d.strftime("%Y-%m-%d")


#------------------------Create Labels-------------------------------#


        # label to display date
        date_label = Label(btm_frame, text=date)
        date_label.pack(side=LEFT)

        # name label
        name_label = Label(frame, text="Enter Name:")
        name_label.grid(row=0, sticky=W)

        # age label
        age_label = Label(frame, text="Enter Age:")
        age_label.grid(row=1, sticky=W)

        # address label
        addr_label = Label(frame, text="Enter Address:")
        addr_label.grid(row=2, sticky=W)

        # city label
        city_label = Label(frame, text="Enter City:")
        city_label.grid(row=3, sticky=W)

        # state label
        state_label = Label(frame, text="Enter State:")
        state_label.grid(row=4, sticky=W)

        # zip code label
        zip_label = Label(frame, text="Enter Zip Code:")
        zip_label.grid(row=5, sticky=W)

        # ssn label
        ssn_label = Label(frame, text="Enter Social Security #:")
        ssn_label.grid(row=6, sticky=W)

        # phone label
        phone_label = Label(frame, text="Enter Phone #:")
        phone_label.grid(row=7, sticky=W)

        # cell label
        cell_label = Label(frame, text="Enter Cell #:")
        cell_label.grid(row=8, sticky=W)


#----------------------Create Vars and Entry-------------------------#


        # name variable and entry
        self.name_var = StringVar()
        self.e1 = Entry(frame, textvariable=self.name_var)
        self.e1.grid(row=0, column=1)

        # age variable and entry
        self.age_var =  IntVar()
        self.e2 = Entry(frame, textvariable=self.age_var)
        self.e2.grid(row=1, column=1)

        # address variable and entry
        self.address_var = StringVar()
        self.e3 = Entry(frame, textvariable=self.address_var)
        self.e3.grid(row=2, column=1)

        # city variable and entry
        self.city_var = StringVar()
        self.e4 = Entry(frame, textvariable=self.city_var)
       self.e4.insert(0, "Roanoke")        # insert default value
       self.e4.grid(row=3, column=1)

        # state variable and entry
        self.state_var = StringVar()
        self.e5 = Entry(frame, textvariable=self.state_var)
        self.e5.insert(0, "VA")             # insert default value
        self.e5.grid(row=4, column=1)

        # zip code variable and entry
        self.zip_var = IntVar()
        self.e6 = Entry(frame, textvariable=self.zip_var)
        self.e6.grid(row=5, column=1)

        # s.s.n variable and entry
        self.ssn_var = StringVar()
        self.e7 = Entry(frame, textvariable=self.ssn_var)
        self.e7.grid(row=6, column=1)

    # phone variable and entry
        self.phone_var = StringVar()
        self.e8 = Entry(frame, textvariable=self.phone_var)
        self.e8.grid(row=7, column=1)

        # cell variable and entry
        self.cell_var = StringVar()
        self.e9 = Entry(frame, textvariable=self.cell_var)
        self.e9.grid(row=8, column=1)

        # quit, search, clear, add, delete buttons
        quit_button = Button(btm_frame, text="Quit", relief=GROOVE, command=parent.destroy)
        quit_button.pack(side=RIGHT)        

        search_button = Button(btm_frame, text="Search", relief=GROOVE, command=self.search)
        search_button.pack(side=RIGHT, padx=1, pady=1)

        clear_button = Button(btm_frame, text="Clear", relief=GROOVE, command=self.clear_entries)
        clear_button.pack(side=RIGHT, padx=1, pady=1)        

        del_button = Button(btm_frame, text="Delete", relief=GROOVE, command=self.del_employee)
        del_button.pack(side=RIGHT, padx=1, pady=1)

        add_button = Button(btm_frame, text="Add", relief=GROOVE, command=self.add_data)
        add_button.pack(side=RIGHT, padx=1, pady=1)


    def add_data(self):        
        name = self.name_var.get()
        age = self.age_var.get()        
        addr = self.address_var.get()
        city = self.city_var.get()
        state = self.state_var.get()
        zip = self.zip_var.get()
        ssn = self.ssn_var.get()
        phone = self.phone_var.get()
        cell = self.cell_var.get()
        # create new Employee in .db
        new_person = Employee(name=name, age=age, address=addr, city=city, state=state, zip=zip, ssn=ssn, phone=phone, cell=cell)
        session.add(new_person)
        session.commit()
        session.close()
        self.callback()
        return        

    def callback(self):        
        showinfo("New Employee", "Data Added")
        self.clear_entries()
        return        

    def clear_entries(self):
        entries = [self.e1, self.e2, self.e3, self.e4, self.e5, self.e6, self.e7, self.e8, self.e9]
        for entry in entries:
            entry.delete(0, END)
        return            

    def search(self):
        search_win = Toplevel()
        search_win.title("Employee Search")

        # create labels for each employee attribute
        attr =   ["Id","Name","Age","Address","City","State","Zip","SSN","Cell","Phone"]
        column = 0
        for a in attr:
                Label(search_win, text=a).grid(row=0,column=column,padx=2, pady=2)
                column += 1

        # search all employees, put each emp. in Entry Widget with For Loop
        res = session.query(Employee).all()
        row = 1
        column = 0
        for employee in res:
            txt = [employee.id, employee.name, employee.age, employee.address, employee.city, employee.state, employee.zip, employee.ssn, employee.phone, employee.cell]
            for t in txt:
                ent = Entry(search_win, relief=RIDGE, width=19)
                ent.grid(row=row, column=column, sticky=W, padx=1, pady=1)
                ent.insert(0, t)
                column += 1
            row += 1
            column = 0
        return

    def del_employee(self):
        del_win = Toplevel()
        del_win.title("Delete Employee")

        id_label = Label(del_win, text="Enter Employee Id:")
        id_label.grid(row=0, column=0, padx=5, pady=5)

        self.employee_id = IntVar()
        self.e10 = Entry(del_win, textvariable=self.employee_id)
        self.e10.grid(row=0, column=1, padx=5, pady=5)

        del_button = Button(del_win, text="Delete Employee", relief=GROOVE, command=self.erase)
        del_button.grid(row=0, column=2, padx=5, pady=5)
        return

    def erase(self):
        emp_id = self.employee_id.get()
        res = session.query(Employee).filter(Employee.id==emp_id).first()
        session.delete(res)
        session.commit()
        showinfo("Employee", "Data Deleted")
        return



if __name__ == '__main__':
    root = Tk()
    root.geometry("310x270")
    root.title("Employee Info")
    mygui = GUI(root)
    root.mainloop()

这是我在更改上面的代码后遇到的第一个错误,将 try:except 子句添加到 add_data 方法中的 age 变量。 . .也就是说,把上面的add_data方法改成这样:

def add_data(self):        
    name = self.name_var.get()
    try:
        age = self.age_var.get()
    except ValueError:
        showinfo("Error:", "Please Enter A Number In Age Field.")
    addr = self.address_var.get()
    city = self.city_var.get()
    state = self.state_var.get()
    zip = self.zip_var.get()   
    ssn = self.ssn_var.get()
    phone = self.phone_var.get()
    cell = self.cell_var.get()
    # create new Employee in .db
    new_person = Employee(name=name, age=age, address=addr, city=city, state=state, zip=zip, ssn=ssn, phone=phone, cell=cell)
    session.add(new_person)
    session.commit()
    session.close()
    self.callback()
    return

当用户在年龄字段中输入一个字符串,然后在显示信息对话框中单击 "ok" 时,我得到这个错误:

    Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
    return self.func(*args)
  File "C:\Python27\test2_gui.py", line 182, in add_data
    new_person = Employee(name=name, age=age, address=addr, city=city, state=state, zip=zip, ssn=ssn, phone=phone, cell=cell)
UnboundLocalError: local variable 'age' referenced before assignment

在你的问题的开头,你有一段代码,然后是“age now becomes a local variable”。这是不可能的,因为 a) 您显示的代码既没有设置也没有使用名为 age 的变量,并且 b) 这不是 try 所做的。您的代码设置了 self.age,但这与名为 age 的局部变量完全不同。

错误消息告诉了您需要知道的一切。如果它说 "local variable 'age' referenced before assignment.",那么您可以相信它说的是字面意思。你必须问自己"why is age (not self.age) local when it I think it's global?",或者"why is age not set when I think that it is?"。 try 语句本身_不会_神奇地使变量局部化。

让我重复最后一行:try 语句本身_not_ 神奇地使变量成为本地变量。 您在评论中链接到的另一个答案给了您不好的建议.

了解正在发生的事情的一种简单的低技术含量的方法是在分配局部变量 age 之后立即放置打印语句,您会看到该行代码没有得到执行。您需要逐步执行您的逻辑,看看为什么它没有被执行。

如果真正的问题是它抱怨一个局部变量 age 而你正在设置一个名为 self.age 的属性,那就是问题 - 将 age 更改为 self.age,然后再次在您设置 self.age 的位置放置一个打印语句,以向您自己证明它是——或不是——在你收到错误之前被设置。

不幸的是,你把你的问题弄得一团糟。我认为有几个不同版本的代码,以及 "the original version" 附带的错误消息,当前版本没有错误。我认为。这真的很难理解。

可能 问题很简单,如果您的 try 在设置变量时发现错误,那么该变量将不会被设置。如果 try 后面有其他代码并使用该变量,它将失败,因为 try 块未能设置该变量。一个简单的解决方案可能是在 catch 块中将变量设置为零。