首页 > 解决方案 > 在 Kivy 中发布的多项操作

问题描述

我可以在发布时在其中添加更多功能,否则将无法正常工作。我想要显示更多的弹出功能和图片,可能是一些音频等。这是.kv文件:

<Root>:

    orientation: 'vertical'
    RecordButton:
        id: record_button
        background_color: 1,1.01,0.90,1
        text: 'Order'
        on_release: 
            self.record()
            root.pop1()
        height: '100dp'
        size_hint_y: None

    TextInput:
        text: record_button.output
        readonly: True

标签: pythonkivy

解决方案


将事件回调定义为语句序列。

KV 文件内部

缩进和结构化控制流的可读性在 KV 文件中受到限制。正如inclement 所评论的,基本上有两种定义回调序列的方法:

  • 每行语句(相同的缩进)
  • 分号分隔的语句
on_release: 
    self.record()
    root.pop1()
on_press: print('pressed'); self.insert_text("pressed!")

见 Kivy 语言语法里面的有效表达式

[..] 多个单行语句是有效的,包括那些转义换行符的语句,只要它们不添加缩进级别。

在 Python 中定义一个函数

您可以更灵活地在 Python 脚本中定义 a 函数并在 KV 文件中的事件上声明此回调。

例如,RecordButton在 Python 中作为方法的函数(假设它是一个扩展 Button 的类):

class RecordButton(Button):
    # callback function tells when button released
    # It tells the state and instance of button.
    def record_and_pop(self, instance):
        print("Button is released")
        print('The button <%s> state is <%s>' % (instance.text, instance.state))
       self.record()
       root.pop1()

然后在 KV 内部使用:

RecordButton:
    on_release: self.record_and_more()

也可以看看


推荐阅读