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

标签 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

最佳答案

我在您的代码中发现两个问题:

  • 首先,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()

输出:

enter image description here

关于python - 如何让 on_press 在自定义按钮中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45178846/

相关文章:

python - 使用 python 将新列从列表 append 到 df

python - 无法运行基于TKinter的python应用程序

python - 高效计算点云的体素指数

python - 神经网络推荐无法让它运行

python - Python 3.7 中的断点()

python - 如果一侧继承自另一侧, __eq__ 的执行顺序是什么?

python - 从数据框列创建一个字典,该字典的单元格中有多个值

python - 刷新/重新加载文件选择器

linux - 为什么错误 urllib.error.ContentTooShortError :

python - 你可以在kivy(python)中的弹出窗口或屏幕上打印表格吗