我在屏幕上添加了一个FloatButton,但我无法将任何On_Release操作与其关联.我怀疑这个问题与以下事实有关:我的FloatButton实际上继承自FloatLayout,因此它没有ON_RELEASE属性? 下面是我在KV文件中的FloatButton定义:

<FloatButton@FloatLayout>:
    id: float_add_button  # Giving id to button
    size_hint: (None, None)
    text: ''
    btn_size: (70, 70)
    size: (70, 70)
    bg_color: (0.404, 0.227, 0.718, 1.0)
    # pos_hint: {'x': .6}
 
    Button:
        text: float_add_button.text
        markup: True
        font_size: 40
        size_hint: (None, None)
        size: float_add_button.btn_size
        pos_hint: {'x': .5, 'y': .8} 
        background_normal: ''
        background_color: (0, 0, 0, 0)
        canvas.before:
            Color:
                rgba: (0.404, 0.227, 0.718, 1.0)
            Ellipse:
                size: self.size
                pos: self.pos

再往下看KV文件,我正在看_Release

<MainWindow>:
    name: 'main'

    RelativeLayout:
        orientation: 'lr-tb'
        size_hint: 1, 1
        padding: '20sp'
        canvas.before:
            Rectangle:
                pos: self.pos
                size: self.size

        # A few buttons here
        #
        #
        #

    FloatButton:
        id: addButton
        text: '+'
        markup: True
        background_color: 1, 0, 1, 0
        pos_hint: {"x":.5,"top":.5}
        on_release:
            print("[TEST] on_release works!")

但是,我得到以下错误:

 Traceback (most recent call last):
   File "C:\Users\gitcanzo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\kivy\lang\builder.py", line 734, in _apply_rule 
     raise AttributeError(key)
 AttributeError: release

 During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
   File "D:\Recipy_project\Recipy\main.py", line 1, in <module>
     from Recipy.app import Recipy
   File "D:\Recipy_project\Recipy\Recipy\app.py", line 21, in <module>
     kv = Builder.load_file("Recipy/ui/layout.kv")
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   File "C:\Users\gitcanzo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\kivy\lang\builder.py", line 310, in load_file   
     return self.load_string(data, **kwargs)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   File "C:\Users\gitcanzo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\kivy\lang\builder.py", line 412, in load_string 
     self._apply_rule(
   File "C:\Users\gitcanzo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\kivy\lang\builder.py", line 665, in _apply_rule 
     child.apply_class_lang_rules(
   File "C:\Users\gitcanzo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\kivy\uix\widget.py", line 470, in apply_class_lang_rules
     Builder.apply(
   File "C:\Users\gitcanzo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\kivy\lang\builder.py", line 545, in apply       
     self._apply_rule(
   File "C:\Users\gitcanzo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\kivy\lang\builder.py", line 741, in _apply_rule 
     raise BuilderException(
 kivy.lang.builder.BuilderException: Parser: File "D:\Recipy_project\Recipy\Recipy\ui\layout.kv", line 590:
 ...
     588:               pos_hint: {"x":.5,"top":.5}
     589:               on_release:
 >>  590:                       print("[TEST] on_release works!")
     591:                       # root.manager.transition.direction = "left"
     592:                       # app.root.current = 'add'
 ...
 AttributeError: release
   File "C:\Users\gitcanzo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\kivy\lang\builder.py", line 734, in _apply_rule 
     raise AttributeError(key)

推荐答案

问题的原因正是您所说的,您的FloatButton类是从FloatLayout派生的,而不是从Button派生的,所以它没有on_release事件.

一种 Select 是在FloatButton类中定义该自定义事件:

class FloatButton(FloatLayout):
    def __init__(self, *args, **kwargs):
        self.register_event_type('on_release')
        super().__init__(*args, **kwargs)

    def on_release(self, *args):
        pass

并在按下内部按钮时发送:

<FloatButton@FloatLayout>:
    # ...
    Button:
        on_release: root.dispatch('on_release')

一个完整的可重现的例子:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout


kv = '''
<FloatButton@FloatLayout>:
    id: float_add_button  # Giving id to button
    size_hint: (None, None)
    text: ''
    btn_size: (70, 70)
    size: (70, 70)
    bg_color: (0.404, 0.227, 0.718, 1.0)
    # pos_hint: {'x': .6}

    Button:
        on_release: root.dispatch('on_release')
        text: float_add_button.text
        markup: True
        font_size: 40
        size_hint: (None, None)
        size: float_add_button.btn_size
        pos_hint: {'x': .5, 'y': .8}
        background_normal: ''
        background_color: (0, 0, 0, 0)
        canvas.before:
            Color:
                rgba: (0.404, 0.227, 0.718, 1.0)
            Ellipse:
                size: self.size
                pos: self.pos


<MainWindow@RelativeLayout>:
    name: 'main'

    FloatButton:
        id: addButton
        text: '+'
        markup: True
        background_color: 1, 0, 1, 0
        pos_hint: {"right":.5,"top":.5}
        on_release:
            print("[TEST] on_release works!")

MainWindow:
'''


class FloatButton(FloatLayout):
    def __init__(self, *args, **kwargs):
        self.register_event_type('on_release')
        super().__init__(*args, **kwargs)

    def on_release(self, *args):
        pass


class MainWindow(App):
    def build(self):
        return Builder.load_string(kv)


if __name__ == '__main__':
    MainWindow().run()

Python相关问答推荐

如何让 turtle 通过点击和拖动来绘制?

TARete错误:类型对象任务没有属性模型'

如何检测背景有噪的图像中的正方形

Python 约束无法解决n皇后之谜

按列分区,按另一列排序

如何访问所有文件,例如环境变量

如何使用LangChain和AzureOpenAI在Python中解决AttribeHelp和BadPressMessage错误?

如何在polars(pythonapi)中解构嵌套 struct ?

如何使用根据其他值相似的列从列表中获取的中间值填充空NaN数据

DataFrames与NaN的条件乘法

如何让这个星型模式在Python中只使用一个for循环?

我如何根据前一个连续数字改变一串数字?

Django Table—如果项目是唯一的,则单行

如何在Python中将超链接添加到PDF中每个页面的顶部?

SpaCy:Regex模式在基于规则的匹配器中不起作用

PYTHON中的selenium不会打开 chromium URL

无法使用请求模块从网页上抓取一些产品的名称

try 在单个WITH_COLUMNS_SEQ操作中链接表达式时,使用Polars数据帧时出现ComputeError

如何在微调Whisper模型时更改数据集?

使用Django标签显示信息