【问题标题】:kivymd refences with ids带有 id 的 kivymd 参考
【发布时间】:2020-12-16 08:33:50
【问题描述】:

我正在尝试使用 id 函数从 MDTextField 引用 text_input,但是我无法理解 id 函数是如何工作的。有谁知道我的代码有什么问题? 第一个代码是主应用程序,第二个代码是所有小部件所在的位置。我已经在互联网上搜索了解决方案,但我不明白为什么我的代码不起作用。

from kivy.lang import Builder
from kivymd.app import MDApp
from kivy.uix.screenmanager import Screen, ScreenManager
from Screen_helper import Home


class MenuScreen(Screen):
    pass


class ProfileScreen(Screen):
    pass


sm = ScreenManager()
sm.add_widget(MenuScreen(name='Menu'))
sm.add_widget(MenuScreen(name='Profile'))


class Mainapp(MDApp):

    def build(self):
        screen = Screen()
        helper = Builder.load_string(Home)
        screen.add_widget(helper)
        key = self.root.ids.username_input
        return screen


Mainapp().run()
Home = '''
ScreenManager:
    MenuScreen:
    ProfileScreen:

<MenuScreen>:
    name: 'Menu'
    MDRectangleFlatButton:
        id: my_button
        text: 'Profile'
        pos_hint: {'center_x': 0.5, 'center_y': 0.1}
        on_press: root.manager.current = 'Profile'
    MDTextField:
        id: username_input
        input_filter: "int"
        hint_text: 'CHIAVE NUMERICA'
        helper_text: 'compresa tra 0 e 95' 
        helper_text_mode: 'on_focus'
        icon_right: 'key-variant'
        icon_right_color: app.theme_cls.primary_color
        pos_hint: {'center_x':0.5,'center_y':0.55}
        size_hint_x:None
        width:230
        input_filter: 'int'
        
        
<ProfileScreen>:
    name: 'Profile'
    MDLabel:
        text: 'Welcome'
        halign: 'center'
    MDRectangleFlatButton:
        text: 'back'
        pos_hint: {'center_x': 0.5, 'center_y': 0.3}
        on_press: root.manager.current = 'Menu' '''

【问题讨论】:

    标签: python function kivymd


    【解决方案1】:

    为 MenuScreen 类提供一个 ID,然后访问该小部件。

    将此添加到 kv 文件中。

    <MenuScreen>:
        id: menu
    

    要访问小部件,您现在可以在 python 中执行此操作:

    key = self.root.menu.ids.username_input
    

    【讨论】:

    • 我尝试向 MenuScreen 类添加一个 Id,但它给了我错误:AttributeError: ‘NoneType’ object has no attribute ‘MenuScreenID’
    • 我已经按照你说的做了,但是它不起作用,它给了我同样的错误
    • 刚刚意识到你是在 build() 函数下做的,在 on_start() 函数下做。
    猜你喜欢
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 2022-06-24
    • 1970-01-01
    相关资源
    最近更新 更多