【问题标题】:Change Kivy button widget attribute by pressing button in another screen通过按下另一个屏幕中的按钮来更改 Kivy 按钮小部件属性
【发布时间】:2014-09-03 23:28:37
【问题描述】:

在我的应用程序中,我有一个 GameScreen,它有一个带有一些文本的 ClueButton1 小部件。按下该按钮将用户带到一个有 4 个按钮的 ClueScreen(使用 kivy 屏幕管理器),每个按钮都是一个答案选项。当用户在 ClueScreen 上按下正确的 ClueAnswerButton1 时,如何更改 GameScreen 上 ClueButton1 的 background_normal 属性?

我已经尝试为 ClueButton1 分配一个 id 并在 def check_choice() 中使用它作为 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'

【问题讨论】:

    标签: python python-2.7 kivy


    【解决方案1】:

    您试图在类对象而不是实例上分配属性。您可以通过ScreenManager 获取另一个屏幕的实例。假设您从根小部件(即root.check_choice())运行它:

    self.manager.get_screen('game_home').cluebutton1id.background_normal = 'path/to/image.png'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      相关资源
      最近更新 更多