有列表时如何在kivymd中切换屏幕

时间:2020-11-03 17:11:27

标签: python kivy kivymd

我创建了一个音乐播放器,并在单击列表时尝试添加切换屏幕的功能,它应该具有切换屏幕的功能,但这给了我我完全不知道的错误。 它说:引发AttributeError(key),“ on_press:root.manager.current ='controller'

也有问题。

对不起,我的代码有点混乱。

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

helper_string = """
ScreenManager:
    MainScreen:
    PlayingScreen:

<MainScreen>:
    name: 'list'
    BoxLayout:
        orientation: "vertical"
        MDToolbar:
            title: "Demo music player"
        ScrollView:
            MDList:
                id: scroll
                on_press: root.manager.current ='controller'


<PlayingScreen>:
    name: 'controller'
    MDLabel:
        text : 'Hello world'
        halight: 'center'

"""

class MainScreen(Screen):
    pass


class PlayingScreen(Screen):
    pass


sm = ScreenManager()
sm.add_widget(MainScreen (name='list'))
sm.add_widget(PlayingScreen (name='controller'))

class MainApp(MDApp):
    def build(self):
        self.sound = None
        self.theme_cls.theme_style="Dark"
        screen = Builder.load_string(helper_string)
        return screen
        
    def on_start(self):
        for root, dirs, files in os.walk('assets'):
            for file in files:
                if file.endswith('.mp3'):
                    required_file = file
                    the_location = os.path.abspath(os.path.join(root, required_file))
                    self.root.ids.scroll.add_widget(OneLineListItem(text=the_location, 
                                                                    on_release=self.play_song))

    
    def play_song(self, onelinelistitem):
        the_song_path = onelinelistitem.text
        if self.sound:
            self.sound.stop()
        self.sound = SoundLoader.load(the_song_path)
        if self.sound:
            self.sound.play()
        print(the_song_path)

    

MainApp().run()

3 个答案:

答案 0 :(得分:0)

尝试以下操作:self.root.current = "insert here the id of screen"

答案 1 :(得分:0)

复制并粘贴以下内容:I changed only this part:

对不起,我的回复很晚 头必须删除“ on_press”:see this

这是正确的代码: MDList: id: scroll on_touch_down: app.root.current ='controller'

答案 2 :(得分:0)

我使用了 on_release,它对我有用,而不是 on_press..