簡體   English   中英

Kivy,ScreenManager:如何訪問另一個屏幕中定義的變量?

[英]Kivy, ScreenManager: how to access a variable defined in another screen?

我正在使用 ScreenManager 編寫一個有兩個屏幕的應用程序。 在一個屏幕中,我有一個文本輸入,以及一個讀取此類文本輸入的按鈕。 如果滿足輸入的某個條件,則激活第二個屏幕。 在這個屏幕上,我希望能夠從第一個屏幕抓取文本輸入的內容。

我進行了多次嘗試並查看了許多類似的問題(例如這個),但它們似乎都沒有真正起作用。

以下是我的代碼的最小非工作版本:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen


class RootWindow(Screen):
    def __init__(self, **kwargs): 
        super(RootWindow, self).__init__(**kwargs)

        box = BoxLayout()
        self.add_widget(box)

        self.searchInput = TextInput(multiline=False)
        box.add_widget(self.searchInput)

        self.searchButton = Button(text="Search")
        self.searchButton.bind(on_press=self.searchRecipe)                                  
        box.add_widget(self.searchButton)

    def searchRecipe(self, instance):
        src = self.searchInput.text
        if not src == "Go":
            pass
        else:  
            WMan.current = 'result'


class ResultWindow(Screen):
    def __init__(self, **kwargs): 
        super(ResultWindow, self).__init__(**kwargs)
        titleBox = BoxLayout()
        self.add_widget(titleBox)        

        print(src)


WMan = ScreenManager()
WMan.add_widget(RootWindow(name='root'))  
WMan.add_widget(ResultWindow(name='result'))


class RecipApp(App):
    def build(self):
        return WMan


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

如果您像這樣保存對titlebox的引用:

class ResultWindow(Screen):
    def __init__(self, **kwargs): 
        super(ResultWindow, self).__init__(**kwargs)
        self.titleBox = BoxLayout()
        self.add_widget(self.titleBox)        

然后您可以通過titlebox訪問標題WMan ,如下所示:

def searchRecipe(self, instance):
    src = self.searchInput.text
    if not src == "Go":
        pass
    else:
        WMan.current = 'result'
        WMan.current_screen.titlebox.add_widget(Label(text=src))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM