简体   繁体   中英

Kivy language function call on button press using screens

I have been fiddling with the Kivy language and have done some searching, but haven't found a solution that works for my situation. I assume I am missing a little fundamental thing here.

I am trying to call a function within a screen from a button press and I want to facilitate this with a kv file. I simplified the code and left out some formatting in kv file, such as layout and button size, etc.

The 'entered' variable is showing up on the screen as "Not Entered", but when I press the button, the label does not change and the function is not entered, nothing happens.

Python:

import kivy
kivy.require('1.9.1')

from kivy.app import App
from kivy.uix.screenmanager import Screenmanager, Screen
from kivy.properties import StringProperty

class ScreenManager(ScreenManager):
    pass

class StartMenu(Screen):
    pass

class MyScreen(Screen):
    entered = StringProperty()
    entered = "Not Entered"

    def my_function(self, *args):
        self.entered = "Entered"

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

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

Kivy: my.kv

#:kivy 1.9.1

<ScreenManager>:
    StartMenu:
    MyScreen:

<StartMenu>:
    name: 'StartMenu'
    Button:
        on_release:
            root.manager.current = 'MyScreen'

<MyScreen>:
    name: 'MyScreen'
    Label:
        text: root.entered
    Button:
        on_release:
            root.my_function()

Thanks for your time!

The problem is here:

class MyScreen(Screen):
    entered = StringProperty()
    entered = "Not Entered"

entered gets overwritten immediately (and is a standard class property, losing all the event magic). Instead initialize it as entered = StringProperty("Not Entered") , or in the kv file as

<MyScreen>:
    entered: "Not Entered"

Btw, to make your example work, there should be some kind of layout:

#:kivy 1.9.1

<ScreenManager>:
    StartMenu:
    MyScreen:

<StartMenu>:
    name: 'StartMenu'
    Button:
        on_release:
            root.manager.current = 'MyScreen'

<MyScreen>:
    entered:"Not Entered"
    name: 'MyScreen'
    GridLayout:
        cols: 2
        Label:
            text: root.entered
        Button:
            on_release:
                root.my_function()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM