如何使用方法更改按钮的 on_release 功能?

How to change on_release function of a button using a method?

我目前正在设计 Android 音乐播放器应用程序。播放歌曲时一切正常。现在,我想要的是,当我们点击播放按钮时,它会将其图像更改为暂停,第一次点击时它将播放歌曲。当我们点击它时它的图像是暂停图像,那么歌曲就会暂停。简单来说,我想更改按钮的 on_release 动作以及单击它时按钮上的图像。

您不必担心如何播放和暂停。我只想知道当我们点击它时如何改变按钮功能和它上面的图像。

我当前的程序是这样的:

from kivy.lang import Builder
from kivymd.uix.list import OneLineListItem
from kivymd.app import MDApp
from kivy.core.audio import SoundLoader
import os

helper_string = """
Screen:
    BoxLayout:
        orientation: "vertical"
        ScrollView:
            MDList:
                id: scroll
        MDRoundImageButton:
            id: play_button
            source: "F:/playbutton.png"
            pos_hint: {"center_x":0.5,"center_y":0.5}
            on_release: app.song_player_on_release_play_button()

"""


class MainApp(MDApp):
    def build(self):
        screen = Builder.load_string(helper_string)
        return screen

    def on_start(self):
        for root, dirs, files in os.walk('C:/'):
            for file in files:
                if file.endswith('.mp3'):
                    required_file = file
                    the_location = os.path.abspath(required_file)
                    self.root.ids.scroll.add_widget(OneLineListItem(text=required_file, on_release=self.play_song))
                    # print(required_file)

    def play_song(self, onelinelistitem):
        SongList = []
        # print('play:', onelinelistitem.text)
        the_song_path = onelinelistitem.secondary_text
        SongList.append(the_song_path)
        if len(SongList) == 1:
            sound = SoundLoader.load(SongList[0])
            if sound:
                sound.play()
            print(the_song_path)
        if len(SongList) > 1:
            SoundLoader.load(SongList[0]).stop()
            sound = SoundLoader.load(SongList[1])
            if sound:
                sound.play()
            print(the_song_path)

    def song_player_on_release_play_button(self):
        self.root.ids.play_button.source = "F:/pause button.png"
        self.root.ids.play_button.on_release = self.song_player_on_release_pause_button()

    def song_player_on_release_pause_button(self):
        self.root.ids.play_button.on_release = self.song_player_on_release_play_button()
        self.root.ids.play_button.source = "F:/playbutton.png"


MainApp().run()

在上面的代码中,我认为如果我使用 self.root.ids.play_button.on_release,那么它会更改发布功能,但它没有用。现在,我陷入了困境:如何更改按钮功能及其上的图像?

我是编程新手,我在 Python 中使用 kivy 和 kivymd 制作这个应用程序。

如果你正在测试这个,请更改图像名称或下载我原来使用的图像:

暂停按钮:

播放按钮:

同样,我希望他们改变彼此的 on_release 动作,这意味着当我们点击暂停时它会打印暂停,改变按钮图像以播放。然后,当我们点击播放时,它会打印播放并将按钮图像更改为暂停,这将永远持续下去......

您不需要为此定义两个函数。在一个功能中,您可以更改播放或暂停图像,如下所示。

    def song_player_on_release_play_button(self, *args):
        if self.root.ids.play_button.source = "F:/playbutton.png":
            self.root.ids.play_button.source = "F:/pause button.png"
        else:
            self.root.ids.play_button.source = "F:/playbutton.png"