通过另一个屏幕上的按钮按压更改Kivy按钮小部件属性
在我的应用程序中,有一个游戏界面(GameScreen),里面有一个叫做ClueButton1的按钮,上面有一些文字。用户点击这个按钮后,会进入一个提示界面(ClueScreen),这个界面上有4个按钮,每个按钮代表一个答案选项。当用户在提示界面上点击正确的答案按钮(ClueAnswerButton1)时,我想要改变游戏界面上ClueButton1的背景。
我已经尝试给ClueButton1设置一个ID,然后在一个叫做check_choice()的函数中使用这个ID,像这样:GameScreen.cluebutton1id.background_normal = ...,但是出现了错误:
AttributeError: 'kivy.properties.ObjectProperty' object has no attribute 'background_normal'
main.py的代码在这里:
class GameScreen(Screen):
...
class ClueScreen(Screen):
...
def check_choice(self):
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'
self.choice0.disabled = True
self.choice1.disabled = True
self.choice2.disabled = True
self.choice3.disabled = True
return
else:
self.message.text = "Try again"
self.choice0.background_disabled_down = 'atlas://img/myatlas/red_button5'
self.choice0.disabled = True
...
而.kv的代码在这里:
<GameScreen>:
GeneralFloatLayout:
GeneralAnchorLayout:
GeneralBoxLayout:
GameGridLayout:
ClueButton1:
text: root.question
on_press: root.manager.current = 'clue_screen';
<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'
1 个回答
3
你正在尝试给类对象设置属性,而不是给它的实例设置。你可以通过 ScreenManager
来获取另一个屏幕的实例。假设你是从根部小部件运行这个代码的(也就是 root.check_choice()
):
self.manager.get_screen('game_home').cluebutton1id.background_normal = 'path/to/image.png'