【问题标题】:ADD command to button in kivy .kv file将命令添加到 kivy .kv 文件中的按钮
【发布时间】:2023-03-18 21:09:01
【问题描述】:

我需要一个代码示例,说明如何在 kivy 的按钮中添加命令,我使用的是 .kv 文件,任何人都可以帮忙。 kv文件

<MyLayout>
BoxLayout:
    orientation:"horizontal"
    size: root.width, root.height
    Button:
        text:"hello"

python 文件

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.uix.label import Label
Builder.load_file("my.kv")
class MyLayout(Widget,App):
     pass
class UiApp(App):
    def build(self):
         return MyLayout()
UiApp().run()

我听说过 kivy 中的 on_press 函数,但你们能告诉我如何在 .kv 文件中使用它吗?

【问题讨论】:

    标签: file pycharm kivy kivy-language python-3.8


    【解决方案1】:

    这是一个非常简单的示例,当您按下按钮时控制台将打印“hello world”。 root.print_hello_world() 将激活您在 .py 文件中定义的函数。

    .kv 文件

    <MyLayout>:
        BoxLayout:
            orientation:"horizontal"
            size: root.width, root.height
            Button:
                text:"hello"
                on_press:
                    root.print_hello_world()
    

    .py 文件

    from kivy.app import App
    from kivy.uix.widget import Widget
    from kivy.lang import Builder
    from kivy.uix.label import Label
    Builder.load_file("my.kv")
    
    class MyLayout(Widget, App):
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
        
        def print_hello_world(self):
            print("Hello world")     
    
    class UiApp(App):
        def build(self):
            return MyLayout()
    
    UiApp().run()
    

    【讨论】:

    • 我真的不想要这个可以代替 print("hello world") 你能在 kivy 或 Button 中添加标签吗?
    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多