AttributeError:'NoneType'对象没有属性'subject'

时间:2017-04-22 14:58:28

标签: python tkinter

我正在创建一个简单的应用程序来管理待办事项。

Todo

我正在尝试使用所选项目的属性填充文本和组合框小部件,但没有成功,因为显然它没有返回。

我得到了:

/usr/bin/python3.5 /home/cali/PycharmProjects/Todo/Todo.py
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__
    return self.func(*args)
  File "/home/cali/PycharmProjects/Todo/Todo.py", line 233, in edit_item
    self.subject_text = task.subject
AttributeError: 'NoneType' object has no attribute 'subject'

这是我的Task类:

class Task:

    def __init__(self, subject, priority):

        self.subject = subject
        self.priority = priority

......这是有问题的功能:

def edit_item(self):

    if len(self.listbox.curselection()) > 0:
        self.edit_button.config(state=DISABLED)
        self.save_button.config(state=NORMAL)
        self.create_add_dialog()

        task = self.find_task(self.listbox.get(ACTIVE))
        self.subject_text = task.subject
        self.priority_combobox = task.priority

    else:
        messagebox.showinfo('Notification', 'Make sure you have tasks selected!')
        self.edit_button.config(state=DISABLED)

def find_task(self, task):

    for x in self.tasks:
        if x.subject == task:
            return x

我如何克服这个问题?

1 个答案:

答案 0 :(得分:0)

find_task中,您遍历任务列表,如果匹配,则返回任务。但是,如果没有,则返回None。因此,在获取类变量之前,应检查任务是否存在:

task = self.find_task(self.listbox.get(ACTIVE))
if task:
    self.subject_text = task.subject
    self.priority_combobox = task.priority
else:  #no such task
    #example
    messagebox.showinfo("Notification","There is no such task named %s"%(self.listbox.get(ACTIVE)))