在KivyMD应用程序中分配之前引用的局部变量'name'



我一直在尝试从我的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)
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条件中缺少缩进。

相关内容

最新更新