在我们的应用程序中,我们有一个 GameScreen,它有一个显示玩家得分 (GameScreen_player1_score) 的 NumericProperty 对象。在一个单独的 ClueScreen(使用 kivy 屏幕管理器)上,我们有一个 ClueAnswerButton1,当按下时它应该会改变玩家在 GameScreen 上的得分。当用户在 ClueScreen 上按下正确的 ClueAnswerButton1 时,我们如何更改玩家在 GameScreen 上得分的 score 属性?
我们尝试在从 GameScreen 中提取的 ClueScreen 中创建 player1_score 变量,但出现错误:
TypeError: attribute name must be string, not 'int'
main.py 代码在这里:
class GameScreen(Screen):
GameScreen_player1_score = NumericProperty(0)
...
class ClueScreen(Screen):
...
def check_choice(self):
player1_score = self.manager.get_screen('game_home').GameScreen_player1_score
if self.choice0.state == 'down':
if self.choice0.text == self.correct:
self.message.text = "[color=006600]Correct! Click back to game and keep" \
"playing![/color]"
self.choice0.background_disabled_down = 'atlas://img/myatlas/green_button5'
setattr(self,player1_score, +10)
return
else:
self.message.text = "Try again"
self.choice0.background_disabled_down = 'atlas://img/myatlas/red_button5'
self.choice0.disabled = True
class GameApp(App):
sm = ScreenManager()
use_kivy_settings = False
def build(self):
self.sm.add_widget(GameScreen(name='game_home'))
self.sm.add_widget(SheddClue0Screen(name='game_clue0'))
return self.sm
if __name__ == '__main__':
GameApp().run()
bingo.kv 代码在这里:
<GameScreen>:
GeneralFloatLayout:
GeneralAnchorLayout:
GeneralBoxLayout:
ScoreGridLayout:
ScoreBoardLabel:
text: '[color=0046C3]Player 1[/color]'
ScoreBoardLabel:
text: str(root._player1_score)
<ClueScreen>:
message: message
choice0: choice0
choice1: choice1
choice2: choice2
choice3: choice3
ClueBoxLayout:
ClueLabel:
text: "[color=0046C3]" + "Put label Here" + "[/color]"
ClueMessage:
id: message
ClueAnswerButton1:
id: choice0
on_press: root.check_choice()
ClueAnswerButton1:
id: choice1
on_press: root.check_choice()
ClueAnswerButton1:
id: choice2
on_press: root.check_choice()
ClueAnswerButton1:
id: choice3
on_press: root.check_choice()
ClueGridLayout:
ReturnButton:
text: 'Back to game'
on_press: root.manager.current = 'game_home'