You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Kivy:如何将实例变量传递至另一个窗口(类)?

Hey, let's figure out why your email isn't getting passed correctly! The main issue here is that you're creating the InfoPage right when the app starts—way before the user has a chance to type anything into the email input. That's why you're not seeing the actual email value show up. Here are a couple of solid fixes:


Fix 1: Update InfoPage's email value when logging in

This approach keeps your initial structure but updates the email data at the right moment (when the user clicks "Login"):

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button

class ConnectPage(FloatLayout):
    def __init__(self, **kwargs):
        super(ConnectPage, self).__init__(**kwargs)
        self.enter_email_id = Label(text="Email:")
        self.add_widget(self.enter_email_id)
        self.email_entered = TextInput(multiline=False)
        self.add_widget(self.email_entered)
        self.login_acc = Button(text="Login")
        self.add_widget(self.login_acc)
        self.login_acc.bind(on_press=self.login_btn)
    
    def login_btn(self, _):
        # Grab the user's inputted email
        user_email = self.email_entered.text
        if not user_email:
            return  # Don't proceed if email is empty
        
        # Get the running app and update InfoPage's email
        app = App.get_running_app()
        info_page = app.sm.get_screen("Info").children[0]
        info_page.email = user_email
        info_page.refresh_email_display()
        
        # Switch to the Info screen
        app.sm.current = "Info"

class InfoPage(GridLayout):
    def __init__(self, **kwargs):
        super(InfoPage, self).__init__(**kwargs)
        self.cols = 1
        self.email = ""
        # Add a label to display the email
        self.email_label = Label(text=f"Your Email: {self.email}")
        self.add_widget(self.email_label)
    
    def refresh_email_display(self):
        # Update the label with the new email value
        self.email_label.text = f"Your Email: {self.email}"
        print(f"Received email: {self.email}")

class ChatApp(App):
    def build(self):
        self.sm = ScreenManager()
        # Set up Connect screen
        self.connect_page = ConnectPage()
        connect_screen = Screen(name="Connect")
        connect_screen.add_widget(self.connect_page)
        self.sm.add_widget(connect_screen)
        
        # Set up Info screen (no email passed yet)
        self.info_page = InfoPage()
        info_screen = Screen(name="Info")
        info_screen.add_widget(self.info_page)
        self.sm.add_widget(info_screen)
        
        return self.sm

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

Key changes here:

  • Removed the email parameter from InfoPage's __init__ (we'll set it later)
  • Added a refresh_email_display method to InfoPage to update the UI when the email changes
  • In login_btn, we grab the user's input, validate it's not empty, then update the existing InfoPage instance before switching screens

Fix 2: Dynamically create InfoPage on login (cleaner approach)

Instead of pre-creating InfoPage, we make it only when the user logs in, so we can pass the email directly:

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button

class ConnectPage(FloatLayout):
    def __init__(self, **kwargs):
        super(ConnectPage, self).__init__(**kwargs)
        self.enter_email_id = Label(text="Email:")
        self.add_widget(self.enter_email_id)
        self.email_entered = TextInput(multiline=False)
        self.add_widget(self.email_entered)
        self.login_acc = Button(text="Login")
        self.add_widget(self.login_acc)
        self.login_acc.bind(on_press=self.login_btn)
    
    def login_btn(self, _):
        user_email = self.email_entered.text
        if not user_email:
            return
        
        app = App.get_running_app()
        # Remove existing Info screen if it exists
        if "Info" in app.sm.screen_names:
            app.sm.remove_widget(app.sm.get_screen("Info"))
        
        # Create InfoPage with the user's email
        info_page = InfoPage(email=user_email)
        info_screen = Screen(name="Info")
        info_screen.add_widget(info_page)
        app.sm.add_widget(info_screen)
        
        app.sm.current = "Info"

class InfoPage(GridLayout):
    def __init__(self, email, **kwargs):
        super(InfoPage, self).__init__(**kwargs)
        self.cols = 1
        self.email = email
        self.add_widget(Label(text=f"Your Email: {self.email}"))
        print(f"Received email: {self.email}")

class ChatApp(App):
    def build(self):
        self.sm = ScreenManager()
        # Only set up Connect screen initially
        self.connect_page = ConnectPage()
        connect_screen = Screen(name="Connect")
        connect_screen.add_widget(self.connect_page)
        self.sm.add_widget(connect_screen)
        
        return self.sm

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

Key changes here:

  • InfoPage now accepts an email parameter in __init__ (since we create it after the user inputs their email)
  • In login_btn, we create the InfoPage and Screen on-demand, passing the user's input directly
  • We check for an existing Info screen to avoid duplicates

内容的提问来源于stack exchange,提问作者ishika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 11:17:30