如何将 Button 小部件和 TextInput 小部件添加到不同的屏幕?

How can i add Button widget and TextInput widget to different screens?

在这个程序中,我有相同的文本输入和按钮 screen.i 想将按钮放在与 textinput.i 不同的屏幕中尝试了 sm.add_widget(self.b)sm.add_widget(self.t) 但它没用。如何将这些小部件放在不同的屏幕上?


代码:

import kivy
from kivy.uix.button import Button
from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen
   
class me (App):
    def __init__(self):
        super().__init__()
        screen = Screen(name='title1')
        sm=ScreenManager()
        
        self.b=Button(text='start',size_hint=(.13,.066), pos_hint= {'center_y': 0.5, 'center_x': 0.5})
        self.f=FloatLayout( )
        self.t=TextInput(size_hint=(1, .1), height=30,) 
        self.f.add_widget(self.b)
        self.f.add_widget(self.t)

        sm.add_widget(screen)
        sm.current = 'title1'
        
    def build(self):
            return self.f

m=me()
m.run()

首先,您必须创建另一个 Screen,然后将小部件添加到您想要的 Screen。这是您的 me App 的修改版本:

class me(App):

    def build(self):
        # create ScreenManager
        sm = ScreenManager()

        # create two Screens
        screen1 = Screen(name='title1')
        screen2 = Screen(name='title2')

        # configure screen1
        self.b = Button(text='start', size_hint=(.13, .066), pos_hint={'center_y': 0.5, 'center_x': 0.5})
        self.b.on_release = partial(setattr, sm, 'current', 'title2')
        self.f = FloatLayout()
        self.f.add_widget(self.b)
        screen1.add_widget(self.f)

        # configure screen2
        self.t = TextInput(size_hint=(1, .1), height=30, )
        screen2.add_widget(self.t)

        # add screens to ScreenManager
        sm.add_widget(screen1)
        sm.add_widget(screen2)

        # return root widget (the ScreenManager)
        return sm

请注意,这使用 build() 方法而不是 __init__() 方法来构建 GUI。这是推荐的方法。