如何让on_press在自定义按钮中工作?

时间:2017-07-18 23:53:47

标签: python python-3.x kivy kivy-language

我正在尝试创建一个自定义按钮,按下时会改变颜色(实际上更改图像上的色调),我甚至无法让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

1 个答案:

答案 0 :(得分:1)

我在你的代码中看到两个问题:

  • 首先,build方法返回testerBuilder.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()

<强>输出:

enter image description here