Kivy按钮点击调用函数报错:参数不匹配与属性缺失求助
Kivy按钮点击调用函数报错的解决方案
错误原因
- 使用
on_press: root.getSingleRows()报错:Thirdwindow.getSingleRows() takes 0 positional arguments but 1 was given
问题出在Python类方法的定义上:类的实例方法必须接收第一个参数self(代表类的实例本身),你的getSingleRows方法没有定义这个参数,Kivy调用时会自动传递实例对象,导致参数数量不匹配。 - 使用
self.getSingleRows()报错:AttributeError: 'Button' object has no attribute 'getSingleRows'
在Button的kv代码中,self指代的是Button实例本身,而getSingleRows是Thirdwindow类的方法,Button对象并没有这个方法,因此报错。
修正步骤
1. 修复Python方法定义
修改Thirdwindow类的getSingleRows方法,添加self参数:
class Thirdwindow(Screen): def getSingleRows(self): # 必须添加self作为第一个参数 connection = sqlite3.connect('book.db') cursor = connection.cursor() print("Connected to database") sqlite_select_query = """SELECT question FROM advanced""" cursor.execute(sqlite_select_query) print("Fetching single row") record = cursor.fetchone() print(record) print("Fetching next row") record = cursor.fetchone() print(record) cursor.close()
2. 保持kv文件的正确调用逻辑
在Thirdwindow的Button中继续使用root.getSingleRows(),因为在<Thirdwindow>的kv规则里,root指代的就是Thirdwindow的实例:
<Thirdwindow>: name: "game_screen" id: game_screen GridLayout: # 补上缺失的冒号,原代码存在语法错误 cols:2 Label: text:"first checkbox" CheckBox: group:"mygroup" on_active: root.checkbox_click(self,self.active,"first checkbox") Label: text:"second radio button" CheckBox: group:"mygroup" on_active: root.checkbox_click(self,self.active,"second radio button") Label: text:"third radio button" CheckBox: group:"mygroup" on_active: root.checkbox_click(self,self.active,"third radio button") Button: text:"Move Next" on_press: root.getSingleRows()
额外提示
- 原kv代码中
GridLayout后缺少冒号,属于语法错误,必须补上才能正常运行。 - Thirdwindow中引用的
checkbox_click方法目前未定义,若后续需要实现该功能,同样要给方法添加self参数并补充逻辑。
内容的提问来源于stack exchange,提问作者John Kennedy
相关产品推荐
相关产品推荐

