如何在KivyMD中对可重用按钮进行编程?

时间:2020-10-08 10:32:30

标签: python kivy kivy-language kivymd

我正在尝试创建一个“ BackButton”,该按钮将出现在多个屏幕中,具有相同的图标,颜色和位置,并且始终执行相同的操作(将用户发送到上一页)。为了减少出错的机会并节省时间,我想对它进行一次编程,然后在需要时从.kv文件加载它。这是我要做什么的简化示例。

main.py

from kivymd.app import MDApp
from kivy.lang.builder import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.uix.button import MDIconButton

class HomeScreen(Screen):
    pass

class ProfileScreen(Screen):
    pass

sm = ScreenManager()
sm.add_widget(HomeScreen(name='home'))
sm.add_widget(ProfileScreen(name='profile'))

class DemoApp(MDApp):
    def build(self):
        screen = Builder.load_file('main.kv')
        return screen

DemoApp().run()

main.kv

#: include kv/homescreen.kv
#: include kv/profilescreen.kv
#: include kv/button.kv

ScreenManager:
    HomeScreen:
    ProfileScreen:

kv / homescreen.kv

<HomeScreen>:
    name: 'home'
    MDIconButton:
        icon: 'account'
        pos_hint: {'center_x':0.5,'center_y':0.6}
        on_press: root.manager.current = 'profile'
        on_press: root.manager.transition.direction = 'left'

kv / profile.kv

<ProfileScreen>:
    name: 'profile'
    MDLabel:
        text: 'profile'
        halign: 'center'
    BackButton:

button.kv

<BackButton>:
    MDIconButton:
        icon: 'arrow-left-thick'
        pos_hint: {'center_x':0.5,'center_y':0.1}
        on_press: root.manager.transition.direction = 'right'
        on_press: root.manager.current = 'DESTINATION'

只要运行此命令,我都会得到:

AttributeError: 'BackButton' object has no attribute 'manager

我不明白。该按钮应该能够为root.manager.current接受一个变量,因为这将是唯一在屏幕之间更改的变量。有人有建议吗?

1 个答案:

答案 0 :(得分:0)

root变量是kv中的预定义变量,它引用封闭规则的根。因此,该root文件中的kv引用了BackButton,它没有manager属性。试试这个:

<BackButton>:
    MDIconButton:
        icon: 'arrow-left-thick'
        pos_hint: {'center_x':0.5,'center_y':0.1}
        on_press: app.root.manager.transition.direction = 'right'
        on_press: app.root.manager.current = 'DESTINATION'

app也是预定义的kv变量,它引用当前的App,并且应用程序有一个root,即您分配的ScreenManager