首页 > 解决方案 > AttributeError:“kivy.properties.ObjectProperty”对象没有属性“background_normal”

问题描述

我正在用 kivy 制作 mp3 播放器,但我遇到了问题。我已经搜索了解决方案,但它们都不适合我。我收到此错误AttributeError: 'kivy.properties.ObjectProperty' object has no attribute 'background_normal',无法解决。请帮我。

我的python代码

class PlaySongScreen(Screen):
    play_btn = ObjectProperty(None)
    def play(self, song_path):
        #function to play the desired song
        if song_path == 'None':
            song_path = songs_list[0]['text']
        mypath = song_path
        mypath = mypath.replace('\\', '\\\\')
        if pg.mixer.music.get_busy() == 0:
            #playing the song
            pg.mixer.music.load(mypath)
            pg.mixer.music.play() 

            #change the play button to pause button
            self.play_btn.background_normal = 'images\\new_pause.jpg' 
            self.play_btn.background_down = 'images\\pause.jpg'

play_function = PlaySongScreen.play

class PlayButton(Factory.Button):
    def on_press(self):
        play_function(PlaySongScreen, song_path=self.text)

我的 .kv 代码

<PlaySongScreen>:
    play_btn: play_pause
    GridLayout:
        cols: 1
        padding: 5
        RelativeLayout:
            Button:
                id: play_pause
                on_press: root.play('None')
                background_normal: 'images\\new_play.jpg'
                background_down: 'images\\play.jpg'
                size_hint: 0.8, 0.9
                pos_hint: {'center_x': 0.5, 'center_y': 0.5}

我得到的错误

File "c:/Users/user/Desktop/Coding/python/Projects/Music Player/music_player.py", line 126, in on_press
 play_function(PlaySongScreen, song_path=self.text)
 File "c:/Users/user/Desktop/Coding/python/Projects/Music Player/music_player.py", line 40, in play
 self.play_btn.background_normal = 'images\\new_pause.jpg'
 AttributeError: 'kivy.properties.ObjectProperty' object has no attribute 'background_normal'

请帮我解决这个错误。

标签: pythonkivy

解决方案


无法使用您发布的代码重现您的错误。但我怀疑在您使用的实际代码中PlayButton,它调用了PlaySongScreen.play. 如果那是您实际上正在做的事情,那么这就是您的问题的原因。如果您访问PlaySongScreen.play,您访问的是ObjectProperty,而不是Button带有 id的play_pause。您必须play_btn通过 的实例而PlaySongScreen不是类本身来访问属性。

您发布的代码的方式是正确的。使用Button设置on_pressroot.play。是的root实例PlaySongScreen


推荐阅读