Pass variables from .py to .kv file

后端 未结 1 896
广开言路
广开言路 2021-01-27 21:27

I am trying to use variables from python file to .kv file so I searched similar questions and found out the way use Property and coded like this:

相关标签:
1条回答
  • 2021-01-27 22:11

    There are two solutions to this problem. Please refer to the solutions and example for details.

    Solution 1: kv file - Using If statement

    The variable, abcd is None when the kv file is parsed. Add if...else... statement to solve the problem.

    Snippet - kv file

    <MyButton@Button>:
        text: "" if app.abcd is None else "contents (%s)"%(app.abcd)
    
        background_color: (255, 255, 255,1)    # white background color
        color: 0, 0, 0, 1    # black color text
    

    Solution 2: Python code - Initialize in build() method

    Initialize variable, abcd in the build() method.

    Snippet - Python code

    class TestApp(App):
        abcd = StringProperty('')
    
        def build(self):
            self.abcd = 'test'
            return ScreenManagement()
    

    Example

    main.py

    from kivy.app import App
    from kivy.uix.screenmanager import ScreenManager, Screen
    from kivy.properties import StringProperty
    
    
    class StationTest(Screen):
        pass
    
    
    class ScreenManagement(ScreenManager):
        pass
    
    
    class TestApp(App):
        abcd = StringProperty('test')
    
        def build(self):
            return ScreenManagement()
    
    
    TestApp().run()
    

    test.kv

    #:kivy 1.11.0
    #:import SlideTransition kivy.uix.screenmanager.SlideTransition
    
    <ScreenManagement>:
        transition: SlideTransition(direction='left')
        StationTest:
    
    <StationTest>:
        name: 'StationTest'
        BoxLayout:
            orientation: 'vertical'
            size_hint: 1, 0.35
            padding: 0, -200, 0, 0
            MyButton:
            MyButton:
            MyButton:
            MyButton:
    
    
    
    <MyButton@Button>:
        # text: "" if app.abcd is None else "contents (%s)"%(app.abcd)
        text: "contents (%s)"%(app.abcd)
    
        background_color: (1, 1, 1, 1)    # white background
        color: 0, 0, 0, 1    # black color text
    

    Output

    0 讨论(0)
提交回复
热议问题