我一直试图从我的 sqlite 数据库中创建一个列表。该列表可以实时追加。一切正常,直到我添加了“if”语句以便实时添加更多列表项。如果我的数据库已填充,即使使用“if”语句,代码也能正常工作,但如果我的数据库没有值,则会发生以下错误
local variable 'name' referenced before assignment
这是代码
def on_start(self):
list_item = ObjectProperty
list_item = []
self.connection = sqlite3.connect('friend_list.db')
self.cursor = self.connection.cursor()
self.cursor.execute("""SELECT * FROM friend_list ;""")
self.connection.row_factory = lambda cursor, row: row[0]
friends = self.connection.execute('SELECT name FROM friend_list').fetchall()
for name in friends:
print(name)
button = OneLineAvatarIconListItem(text = name,on_press=lambda widget:self.change_screen("Chat_Screen"))
self.root.ids["Chat_List"].ids["list"].add_widget(button)
button.bind(on_press=self.press)
list_item.append(name)
if name not in list_item: #this is the condition which is causing error
a = list_item[-1]
button = OneLineAvatarIconListItem(text = (a),on_press=lambda widget:self.change_screen("Chat_Screen"))
button.bind(on_press=self.press)
self.root.ids["Chat_List"].ids["list"].add_widget(button)
button.bind(on_press=self.press)
print(list_item)
答案 0 :(得分:1)
def on_start(self):
list_item = ObjectProperty
list_item = []
self.connection = sqlite3.connect('friend_list.db')
self.cursor = self.connection.cursor()
self.cursor.execute("""SELECT * FROM friend_list ;""")
self.connection.row_factory = lambda cursor, row: row[0]
friends = self.connection.execute('SELECT name FROM friend_list').fetchall()
for name in friends:
print(name)
button = OneLineAvatarIconListItem(text = name,on_press=lambda widget:self.change_screen("Chat_Screen"))
self.root.ids["Chat_List"].ids["list"].add_widget(button)
button.bind(on_press=self.press)
list_item.append(name)
if name not in list_item: #this is the condition which is causing error
a = list_item[-1]
button = OneLineAvatarIconListItem(text = (a),on_press=lambda widget:self.change_screen("Chat_Screen"))
button.bind(on_press=self.press)
self.root.ids["Chat_List"].ids["list"].add_widget(button)
button.bind(on_press=self.press)
print(list_item)
if 条件中缺少缩进。