我正在尝试创建一个自定义按钮,按下时会改变颜色(实际上更改图像上的色调),我甚至无法让on_press正常工作。应用程序运行,但按下按钮会出现错误:“属性错误:'ImageButton'对象没有属性'change_color'”
python文件:
import kivy
kivy.require("1.10.0")
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.lang.builder import Builder
class Container(BoxLayout):
pass
class ImageButton():
def change_color(self):
print("Success!")
class TestName(App):
def build(self):
return tester
tester = Builder.load_file("test.kv")
if __name__ == '__main__':
TestName().run()
Kivy文件:
Container:
<Container>:
BoxLayout:
ImageButton:
source: "emptybox.png"
<ImageButton@Button>:
source: None
on_press: root.change_color()
Image:
source: root.source
pos: root.pos
size: root.size
答案 0 :(得分:1)
我在你的代码中看到两个问题:
首先,build
方法返回tester
(Builder.load_file
的输出)。
另一方面,.py文件中的ImageButton
类应继承自kivy.uix.button.Button
。
我不知道你想改变什么“颜色”,我给你举个例子,你在按下时改变背景颜色:
import kivy
kivy.require("1.10.0")
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.lang.builder import Builder
from random import random
kv_text = '''
<Container>:
BoxLayout:
ImageButton:
source: "emptybox.png"
<ImageButton@Button>:
source: None
on_press: self.change_color()
Image:
source: root.source
pos: root.pos
size: root.size
'''
class Container(BoxLayout):
pass
class ImageButton(Button):
def change_color(self):
self.background_color = (random(), random(), random(), 1)
class TestName(App):
def build(self):
Builder.load_string(kv_text)
return Container()
if __name__ == '__main__':
TestName().run()
<强>输出:强>