如何在Kivy按下按钮时更改屏幕尺寸

时间:2018-03-22 20:52:37

标签: python python-3.x kivy kivy-language

我尝试使用Window.size(height,widht)和Config,但它无法使用Screen Manager

1 个答案:

答案 0 :(得分:0)

解决方案

在每个屏幕中添加方法( on_enter on_pre_enter )并使用 Window.size ,如以下示例所示。

实施例

main.py

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.window import Window


class MyScreenManager(ScreenManager):
    pass


class Main(Screen):
    def on_pre_enter(self):
        Window.size = (900, 600)


class Login(Screen):
    def on_pre_enter(self):
        Window.size = (400, 300)

    def check_password(self, instance, password):
        if password == "pwd":
            instance.current = "screen2"


class Screen2(Screen):
    pass


class TestApp(App):
    def build(self):
        return MyScreenManager()


if __name__ == "__main__":
    TestApp().run()

test.kv

#:kivy 1.10.0

<MyScreenManager>:
    Main:
    Login:
        id: login
    Screen2:

<Main>:
    name: "main"
    BoxLayout:
        orientation: "horizontal"
        Label:
            text: "Hello"
        Button:
            text: "Go to Login Screen"
            on_press: root.manager.current = "screen1"
<Login>:
    name: "screen1"
    GridLayout:
        size_hint: (0.5, 0.5)
        pos_hint: {"center_x": 0.5, "center_y": 0.6}
        rows: 3
        padding: 20

        Label:
            size_hint: (0.2, 0.2)
            text:"Password:"
            font_size: 30
            halign: "center"
            valign: "middle"

        TextInput:
            id: password
            size_hint: (0.2, 0.06)
            cursor_blink: True
            font_size: 20
            multiline: False
            password: True

        Button:
            text: "Continue"
            size_hint: (0.2, 0.08)
            on_release:
                root.manager.ids.login.check_password(root.manager, password.text)

<Screen2>:
    name: "screen2"
    BoxLayout:
        orientation: "horizontal"
        Label:
            text: "Hello"
        Button:
            text: "Go to screen 1"
            on_press: root.manager.current = "screen1"

输出

Img01 - App Startup Img02 - Login Screen