所以我正在和一些朋友一起做一个项目,我们正在尝试将幸运抽奖的元素融入到 Kivy 上使用 ScreenManager 打开不同的窗口,但我正在努力寻找一种将其应用到代码中的方法。
我也想过使用随机模块,但我不知道从哪里开始。并且在“””“””部分中使用随机函数也不起作用,所以我没有主意了。
我对 Kivy 还很陌生,所以任何帮助将不胜感激。我不只是在寻找可以复制并粘贴到 Visual Studio 中的一大段代码,而是在寻找一些如何将其合并的想法和方法,以便我可以真正了解正在发生的事情。
这就是我想要实现的目标:
这是我目前正在编写的代码:
from kivymd.app import MDApp
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang.builder import Builder
from kivy.uix.widget import Widget
import random
scene_manager = """
ScreenManager:
MenuScreen:
Scene1:
Scene2:
Scene3:
Scene4:
Scene5:
<MenuScreen>:
name: 'menuscreen'
MDRectangleFlatButton:
text: 'Click to draw'
pos_hint: {'center_x':0.5,'center_y':0.6}
on_press: root.manager.current = ??? idk
<Scene1>:
name: 'scene1'
MDLabel:
text: "This is the first path"
halign: "center"
<Scene2>:
name: 'scene2'
MDLabel:
text: "This is the second path"
halign: "center"
<Scene3>:
name: 'scene3'
MDLabel:
text: "This is the third path"
halign: "center"
<Scene4>:
name: 'scene4'
MDLabel:
text: "This is the fourth path"
halign: "center"
<Scene5>:
name: 'scene5'
MDLabel:
text: "This is the fifth path"
halign: "center"
"""
class MenuScreen(Screen):
pass
class Scene1(Screen):
pass
class Scene2(Screen):
pass
class Scene3(Screen):
pass
class Scene4(Screen):
pass
class Scene5(Screen):
pass
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menuscreen'))
sm.add_widget(Scene1(name='scene1'))
sm.add_widget(Scene2(name='scene2'))
sm.add_widget(Scene3(name='scene3'))
sm.add_widget(Scene4(name='scene4'))
sm.add_widget(Scene5(name='scene5'))
class Test(MDApp):
def build(self):
screen = Builder.load_string(scene_manager)
return screen
Test().run()
您可以在例如
App
: 中定义一个方法
class Test(MDApp):
def do_random_screen(self):
screen = random.choice(self.root.screens)
while screen == self.root.current_screen:
screen = random.choice(self.root.screens)
self.root.current = screen.name
然后在你的
kv
中使用该方法:
<MenuScreen>:
name: 'menuscreen'
MDRectangleFlatButton:
text: 'Click to draw'
pos_hint: {'center_x':0.5,'center_y':0.6}
# on_press: root.manager.current = ??? idk
on_press: app.do_random_screen()