Kivy应用为Popup绑定按钮时触发__init__参数数量错误如何解决
错误原因
报错的核心是Kivy及KivyMD组件的构造方法不支持将属性作为位置参数传入,所有自定义属性都需要以关键字参数的形式传递。你写的Button("Removed")相当于给按钮的__init__方法传入了2个位置参数:第一个是类实例自身的self(自动传入),第二个是你手动填写的"Removed"字符串,不符合Button类的参数定义规则,因此触发类型错误。
修复方案
将报错行的按钮创建代码改为显式指定text关键字参数即可解决:
# 原错误代码 # box.add_widget(Button("Removed", on_press=pop.dismiss)) # 修正后代码 box.add_widget(Button(text="Removed", on_press=pop.dismiss))
补充注意事项
你当前的代码还存在弹窗布局逻辑问题:你已经创建了带按钮的BoxLayout容器,但弹窗的content直接指定为了Image组件,会导致按钮无法显示在弹窗中,建议调整为如下逻辑:
if condition == "Bad": print("Bad tool") tool_img = "Capture.png" box = BoxLayout(orientation="vertical", padding=(10)) # 先将图片加入布局容器 box.add_widget(Image(source=tool_img)) # 再添加关闭按钮 box.add_widget(Button(text="Removed", on_press=pop.dismiss)) # 将完整布局容器设为弹窗内容 pop = Popup(title="Faulty tool detected", auto_dismiss=True, content=box, size_hint=(None,None), size=(450,520)) pop.open()
内容的提问来源于stack exchange,提问作者Jolin
相关产品推荐
相关产品推荐

