使用ScreenManager将图片作为按钮时出现Invalid property name错误
正常运行的代码
<MainWindow>: name:'Main' BoxLayout: orientation:'horizontal' size: root.width, root.height Button: text:'Hello' font_size:32 color:1,1,1,1 on_press: app.root.current='second' root.manager.transition.direction = 'right'
修改后报错的代码
<MainWindow>: name:'Main' BoxLayout: orientation:'horizontal' size: root.width, root.height Button: #text:'Hello' #font_size:32 #color:1,1,1,1 Image: source:'photo.png' on_press: app.root.current='second' root.manager.transition.direction = 'right'
错误信息
>> 29: app.root.current='second' 30: root.manager.transition.direction = 'right' 31: ... Invalid property name
问题原因及解决办法
问题出在Button内部直接嵌套Image的写法不符合Kivy的语法规则。Button并非容器控件,不能直接将Image作为子元素放置,这种写法会被Kivy误判为属性定义,从而抛出"无效属性名"的错误。
方法一:使用Button的背景属性设置图片
这是最简便的方式,利用Button自带的background_normal和background_down属性设置常态及点击态的图片:
<MainWindow>: name:'Main' BoxLayout: orientation:'horizontal' size: root.width, root.height Button: background_normal: 'photo.png' # 可选:设置点击时显示的图片 # background_down: 'photo_pressed.png' on_press: app.root.current='second' root.manager.transition.direction = 'right'
方法二:在Button的Canvas中绘制图片
如果需要自定义图片的大小、位置等样式,可以在Button的canvas.before或canvas中绘制Image:
<MainWindow>: name:'Main' BoxLayout: orientation:'horizontal' size: root.width, root.height Button: on_press: app.root.current='second' root.manager.transition.direction = 'right' canvas.before: Color: rgba: 1, 1, 1, 1 # 设置图片透明度,全不透明 Rectangle: source: 'photo.png' pos: self.pos size: self.size
内容的提问来源于stack exchange,提问作者Fantom
相关产品推荐
相关产品推荐

