gpt4 book ai didi

python - Kivy 将小部件添加到屏幕

转载 作者:行者123 更新时间:2023-12-01 04:41:28 27 4
gpt4 key购买 nike

这似乎是一个愚蠢的问题。但我有一个小部件想要添加到名为 GameScreen 的屏幕上。

这是我的 Python 代码:

class WelcomeScreen(Screen):
pass

class BasicScreen(Screen):
pass

class GameScreen(Screen):
parent = Widget()
game = ShootingGame()
parent.add_widget(game)
Clock.schedule_interval(game.update, 1.0 / 60.0)
# return parent

sm = ScreenManager()
sm.add_widget(WelcomeScreen(name='welcome'))
sm.add_widget(BasicScreen(name='basic'))
sm.add_widget(GameScreen(name='game'))

class ShootingApp(App):
def build(self):
print(sm.current)
return sm

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

这是我的 kivy 代码:

<WelcomeScreen>:
Button:
text: "Learn about haptic illusions"
size_hint: None, None
size: 500, 70
pos: 100, 200
font_size: 30
on_release: app.root.current = "basic"

Button:
text: "Play our game"
size_hint: None, None
size: 500, 70
pos: 100, 100
font_size: 30
on_release: app.root.current = "game"

<BasicScreen>:
name: "basic"

<GameScreen>:
name: "game"

我收到的错误是这样的。我认为这是因为我已经为小部件游戏定义了一个父级。但是,我需要该父级,因为游戏小部件使用其父级的宽度和高度值(例如 self.parent.width)。是否有任何解决方法,以便游戏小部件可以嵌套在父级中并将父级添加到屏幕?

kivy.uix.widget.WidgetException: Cannot add <Screen name='game'>, it already has a parent <kivy.uix.widget.Widget object at 0x1093dc8d8>

谢谢大家!!

最佳答案

你可以做这样的事情

class GamesScreen(Screen):
def __init__(self, **kwargs):
super(GameScreen, self).__init__(**kwargs)
self.game = ShootingGame()
self.add_widget(self.game)
clock.schedule_interval(self.game.update, 1.0 / 60.0)

关于python - Kivy 将小部件添加到屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30632327/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com