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

如何在Kivy的.py文件中随机选择屏幕并在.kv文件中调用?

Hey there! Let's get your random screen selection working smoothly. First, let's fix up your Python code since there are a few small issues preventing it from working as expected, then we'll tie it into your .kv file.

Step 1: Fix the Python Class

Your original class has a couple syntax and logic gaps. Here's the corrected version with explanations:

import random
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import StringProperty

class SelectionScreen(Screen):
    # Define the property as an instance-level property (works with Kivy's binding system)
    testScreen = StringProperty('Screen1')

    def screenSelector(self):
        screenList = ['Screen1', 'Screen2']
        # Use random.choice() for cleaner list selection instead of manual indexing
        selected_screen = random.choice(screenList)
        # Update the instance property so the .kv file can access it
        self.testScreen = selected_screen
        return selected_screen

# You'll need to define your actual screen classes too
class Screen1(Screen):
    pass

class Screen2(Screen):
    pass

class MyApp(App):
    def build(self):
        sm = ScreenManager()
        # Add all your screens to the manager with matching names
        sm.add_widget(SelectionScreen(name='selection'))
        sm.add_widget(Screen1(name='Screen1'))
        sm.add_widget(Screen2(name='Screen2'))

        # Optional: Auto-select a random screen on app start
        selection_screen = sm.get_screen('selection')
        selected_screen = selection_screen.screenSelector()
        sm.current = selected_screen

        return sm

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

Key fixes here:

  • Added proper inheritance from Screen (required for Kivy screen properties and integration)
  • Imported the random module (you forgot this in your original code!)
  • Updated testScreen to be an instance property (using self. when updating it) so the .kv file can react to changes
  • Swapped random.randint() for random.choice() to simplify selecting from the list
Step 2: Connect to the .kv File

Now update your .kv file to either trigger the selection manually (via a button) or use the auto-selected screen. Here's a complete example structure:

<SelectionScreen>:
    # Add a button to let users trigger random selection
    Button:
        text: "Pick Random Screen"
        size_hint: 0.5, 0.1
        pos_hint: {'center_x': 0.5, 'center_y': 0.5}
        on_press:
            # Call the selection method, then switch to the chosen screen
            root.screenSelector()
            app.root.current = root.testScreen

<Screen1>:
    Label:
        text: "You're on Screen 1!"
        font_size: 30
        pos_hint: {'center_x': 0.5, 'center_y': 0.5}

<Screen2>:
    Label:
        text: "You're on Screen 2!"
        font_size: 30
        pos_hint: {'center_x': 0.5, 'center_y': 0.5}

How It Works

  • If you added the auto-selection in MyApp.build(), the app will jump straight to a random screen when it starts.
  • The button in SelectionScreen lets users trigger a new random selection at any time—when pressed, it calls screenSelector() to update testScreen, then tells the ScreenManager to switch to that screen.

Just make sure your screen names in the ScreenManager match exactly what's in your screenList (case-sensitive!)—that's a common gotcha.

内容的提问来源于stack exchange,提问作者I.K.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:04:37