按下按钮后如何更改TextInput文本

时间:2019-03-15 03:53:37

标签: python kivy

123 Button后,我该怎么办才能看到'Show 123'的文字?

当我取消注释Clock.schedule_interval时可以使用,但是我需要将此文本进行编辑。我同时看到了"trigger""show"的打印,但是输入中未显示文本'123'

我需要它来处理这两个类。

from kivy.config import Config
Config.set('graphics', 'multisamples', '0')
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout

kv = '''
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
ScreenManagement:
    transition: FadeTransition()
    Show:

<First>:               
    Button:
        text: "Show 123"
        on_press: root.trigger_show()
<Second>:
    TextInput:
        id: textinput                
<Show>
    BoxLayout:
         First:
        Second:
'''

class ScreenManagement(ScreenManager):
    pass

class Show(Screen):
    pass

class First(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def trigger_show(self):
        print("trigger")
        s = Second()
        s.show()

class Second(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        #Clock.schedule_interval(self.show, 1)

    def show(self): #(self, dt):
        print('show')
        self.ids.textinput.text = '123'

sm = Builder.load_string(kv)

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

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

1 个答案:

答案 0 :(得分:3)

在trigger_show中创建的Second与在.kv中创建的Second不同,也就是说,它在未显示的小部件中设置文本,这是临时变量,因为它是局部变量。

在创建类时,必须在整个类中公开内部元素的信号或事件。在这种情况下,我会将Button的on_press事件显示给First,将TextInput的text属性显示给Second,然后在两个元素都存在的范围内建立连接:

from kivy.config import Config
Config.set('graphics', 'multisamples', '0')
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout

kv = '''
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
ScreenManagement:
    transition: FadeTransition()
    Show:

<First>:               
    Button:
        text: "Show 123"
        on_press: root.dispatch('on_press')
<Second>:
    text: ""
    TextInput:
        id: textinput  
        text: root.text              
<Show>
    BoxLayout:
        First:
            on_press:
                second.text = "123"
        Second:
            id: second
'''

class ScreenManagement(ScreenManager):
    pass

class Show(Screen):
    pass

class First(BoxLayout):
    def __init__(self, **kwargs):
        self.register_event_type('on_press')
        super().__init__(**kwargs)

    def on_press(self):
        pass

class Second(BoxLayout):
    pass

sm = Builder.load_string(kv)

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

if __name__ == '__main__':
    TestApp().run()
相关问题