【问题标题】:How to change screen by calling a method in Python Kivy如何通过调用 Python Kivy 中的方法来更改屏幕
【发布时间】:2020-06-12 23:49:47
【问题描述】:

我是 kivy 的新手,我想通过单击图像来更改我的屏幕。我使用了 ButtonBehavior 并调用了我的类 ImageButton 的 on_press 方法,但我无法弄清楚要放置什么代码。我在我的 kivy 文件上尝试了 on_press: screen_manager.current = 'window1' 但它不起作用

Python 代码

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image
from kivy.uix.behaviors import ButtonBehavior


class Window1(Screen):
    pass

class Window2(Screen):
    pass

class WindowManager(ScreenManager):
    pass

class ImageButton(ButtonBehavior, Image):
    def on_press(self):
        # what to call

class Phone(FloatLayout):
    pass


class MyApp(App):
    def build(self):
        return Phone()

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

kv 文件

<Phone>:
    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'top'
        WindowManager:
            id: screen_manager
            size_hint: 1, 0.9
            anchor_y: 'top'
            transition: FadeTransition()
            Window1:
            Window2:

    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'bottom'
        BoxLayout:
            canvas:
                Color:
                    rgba: 228, 241, 254, 1
                Rectangle:
                    size: self.size
            orientation: 'horizontal'
            size_hint: 1, .1
            ImageButton:
                source: 'pic1.png'
                on_press: self.on_press()
            ImageButton:
                source: 'pic2.png'
                on_press: self.on_press()


<Window1>:
    name: 'window1'
    Label:
        text: 'Window1'
<Window2>:
    name: 'window2'
    Label:
        text: 'Window2'

【问题讨论】:

    标签: python-3.x kivy-language


    【解决方案1】:

    有人帮我解决这个问题。我缺少的是我应该放入的 kv 文件中

    on_press: app.root.ids._screen_manager.current = 'window1'

    这里是解释

    在解析 kv 代码时,id 字段进入一个名为 ids 的字典,其中存储指向小部件对象的指针。

    每个 kivy 规则都有一个单独的 id 名称空间。

    分解:

    app.root.ids.screen_manager

    应用就是你的应用

    root 是根小部件,电话

    ids 是在根级别定义的 id 的字典

    埃利奥特·加布斯的功劳

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多