Kivy ids in python code

后端 未结 1 996
挽巷
挽巷 2021-01-26 21:49

main:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayo         


        
相关标签:
1条回答
  • 2021-01-26 22:07

    from functools import partial

    To access the textinput in your external method, you could use partial functions or lambda function.

    self.ids

    You are getting None or empty dictionary because you don't have a kv file.

    Note

    When your kv file is parsed, kivy collects all the widgets tagged with id’s and places them in this self.ids dictionary type property.

    Please refer to my example below for deatils.

    Example

    main.py

    from kivy.app import App
    from kivy.uix.button import Button
    from kivy.uix.screenmanager import ScreenManager, Screen
    from kivy.uix.boxlayout import BoxLayout
    from kivy.uix.label import Label
    from kivy.uix.textinput import TextInput
    from functools import partial
    
    
    class testclass:
        def someth(*args, txt):
            print(txt)
    
    
    class BeginScreen(Screen):
        def __init__(self, **kwargs):
            super(BeginScreen, self).__init__(**kwargs)
            layout = BoxLayout(orientation='vertical', padding=20, spacing=5)
            layout.add_widget(Label(text=str('Hello')))
            layout.add_widget(TextInput(id='test', text=''))
            layout.add_widget(Button(text='Button!', on_press=partial(testclass.someth, txt='?')))
            self.add_widget(layout)
            print("self.ids={}".format(self.ids))
    
    
    class TestApp(App):
        from kivy.config import Config
        Config.set('graphics', 'width', '800')
        Config.set('graphics', 'height', '400')
    
        def build(self):
            sm = ScreenManager()
            sm.add_widget(BeginScreen(name='test'))
            return sm
    
    TestApp().run()
    

    Output

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