Python,KivyMD 从文本字段中获取数据

0 python kivy

几个星期以来,我使用 KivyMD 并且我爱上了这个 Kivy 主题。这是我的问题:我正在使用 KivyMD 制作一个多屏幕应用程序,我的第一个屏幕是“登录屏幕”。我想在我的主类中添加一个函数,该函数获取我的“用户名”文本字段和“密码”文本字段的值。如果标识符正确,我将转到“screen2”。

这是我的代码:

from kivy.app import App
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivymd.theming import ThemeManager

class MyLayout(BoxLayout):

    scr_mngr = ObjectProperty(None)

    def change_screen(self, screen, *args):
        self.scr_mngr.current = screen


KV = """
#:import Toolbar kivymd.toolbar.Toolbar
#:import ThemeManager kivymd.theming.ThemeManager
#:import MDNavigationDrawer kivymd.navigationdrawer.MDNavigationDrawer
#:import NavigationLayout kivymd.navigationdrawer.NavigationLayout
#:import NavigationDrawerDivider 
kivymd.navigationdrawer.NavigationDrawerDivider
#:import NavigationDrawerToolbar 
kivymd.navigationdrawer.NavigationDrawerToolbar
#:import NavigationDrawerSubheader 
kivymd.navigationdrawer.NavigationDrawerSubheader
#:import MDCheckbox kivymd.selectioncontrols.MDCheckbox
#:import MDSwitch kivymd.selectioncontrols.MDSwitch
#:import MDList kivymd.list.MDList
#:import OneLineListItem kivymd.list.OneLineListItem
#:import TwoLineListItem kivymd.list.TwoLineListItem
#:import ThreeLineListItem kivymd.list.ThreeLineListItem
#:import OneLineAvatarListItem kivymd.list.OneLineAvatarListItem
#:import OneLineIconListItem kivymd.list.OneLineIconListItem
#:import OneLineAvatarIconListItem kivymd.list.OneLineAvatarIconListItem
#:import MDTextField kivymd.textfields.MDTextField
#:import MDSpinner kivymd.spinner.MDSpinner
#:import MDCard kivymd.card.MDCard
#:import MDSeparator kivymd.card.MDSeparator
#:import MDDropdownMenu kivymd.menu.MDDropdownMenu
#:import get_color_from_hex kivy.utils.get_color_from_hex
#:import colors kivymd.color_definitions.colors
#:import SmartTile kivymd.grid.SmartTile
#:import MDSlider kivymd.slider.MDSlider
#:import MDTabbedPanel kivymd.tabs.MDTabbedPanel
#:import MDTab kivymd.tabs.MDTab
#:import MDProgressBar kivymd.progressbar.MDProgressBar
#:import MDAccordion kivymd.accordion.MDAccordion
#:import MDAccordionItem kivymd.accordion.MDAccordionItem
#:import MDAccordionSubItem kivymd.accordion.MDAccordionSubItem
#:import MDThemePicker kivymd.theme_picker.MDThemePicker
#:import MDBottomNavigation kivymd.tabs.MDBottomNavigation
#:import MDBottomNavigationItem kivymd.tabs.MDBottomNavigationItem

#:import partial functools.partial

MyLayout:
    scr_mngr: scr_mngr
    orientation: 'vertical'

    ScreenManager:
        id: scr_mngr
        Screen:
            name: 'screen1'
            MDCard:
                size_hint: None, None
                size: dp(520), dp(340)
                pos_hint: {'center_x': 0.5, 'center_y': 0.5}
                BoxLayout:
                    orientation:'vertical'
                    padding: dp(20)
                    spacing:20
                    MDLabel:
                        text: 'Connexion'
                        theme_text_color: 'Secondary'
                        font_style:"Title"
                        size_hint_y: None
                        height: dp(36)
                    MDSeparator:
                        height: dp(1)
                    MDTextField:
                        id: 'username'
                        hint_text: "Username "
                        helper_text_mode: "on_focus"
                    MDTextField:
                        id: 'password'
                        hint_text: "Password "
                        helper_text_mode: "on_focus"

                    MDFlatButton:
                        text: "Connexion"
                        pos_hint: {'center_x': 0.5}
                        on_release: root.check_data_login()
        Screen:
            name: 'screen2'
            Toolbar:
                id: toolbar
                title: "Welcome ! "
                pos_hint: {'center_x': 0.5, 'center_y': 0.97}
                md_bg_color: app.theme_cls.primary_color
                background_palette: 'DeepPurple'
                background_hue: 'A400'
                left_action_items: [['arrow-left', p 
                    partial(root.change_screen, 'screen1') ]]
                right_action_items: [['animation', lambda x: M 
                    MDThemePicker().open()]]

            MDLabel:
                font_style: 'Title'
                theme_text_color: 'Primary'
                text: "Data :"
                height: self.texture_size[1] + dp(3)
                halign: 'center'
                pos_hint: {'center_x': 0.5, 'center_y': 0.85}




"""


class MyApp(App):
    theme_cls = ThemeManager()

    def build(self):
        return Builder.load_string(KV)


    def check_data_login(self):
        username = self.username.text
        password= self.password.text

        print(username)
        print(password)

MyApp().run()
Run Code Online (Sandbox Code Playgroud)

iko*_*lim 7

解决方案

解决方案是使用 Kivy ObjectProperty 连接到 id。详情请参考示例。

kv文件

添加以下 id 和 ObjectProperties

  1. 添加 id: screen1
  2. 添加对象属性, screen1: screen1
  3. id 不是字符串。从id: usernameand 中删除引号id: password
  4. 添加对象属性, username: username
  5. 添加对象属性, password: password
  6. 添加password: True到 TextInput 以便屏蔽密码

片段 - kv 文件

ScreenManager:
    id: scr_mngr
    screen1: screen1

    Screen:
        id: screen1
        name: 'screen1'
        username: username
        password: password

        MDCard:
            ...
                MDTextField:
                    id: username
                    hint_text: "Username "
                    helper_text_mode: "on_focus"

                MDTextField:
                    id: password
                    hint_text: "Password "
                    helper_text_mode: "on_focus"
                    password: True
Run Code Online (Sandbox Code Playgroud)

蟒蛇文件

  1. 移动check_data_login()方法从class MyApp()进入class MyLayout()
  2. 替换self.username.textself.scr_mngr.screen1.username.text
  3. 替换self.password.textself.scr_mngr.screen1.password.text
  4. 添加if语句来检查用户名和密码

片段 - Python 文件

class MyLayout(BoxLayout):

    scr_mngr = ObjectProperty(None)

    def check_data_login(self):
        username = self.scr_mngr.screen1.username.text
        password = self.scr_mngr.screen1.password.text

        print(username)
        print(password)

        if username == "KivyMD" and password == "kivy":
            self.change_screen("screen2")
Run Code Online (Sandbox Code Playgroud)

Kivy 文档

kv 文件的语法

如果小部件没有给定名称的属性,则会自动创建一个 ObjectProperty 并将其添加到小部件中。

引用小部件 » ids

警告

为 id 赋值时,请记住该值不是字符串。没有引号:good -> id: value, bad -> id: 'value'

在你的 Python 代码中访问 Kv lang 中定义的小部件

通常认为使用 ObjectProperty 是“最佳实践”。这将创建一个直接引用,提供更快的访问并且更加明确。

例子

主文件

from kivy.app import App
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivymd.theming import ThemeManager


class MyLayout(BoxLayout):

    scr_mngr = ObjectProperty(None)

    def check_data_login(self):
        username = self.scr_mngr.screen1.username.text
        password = self.scr_mngr.screen1.password.text

        print(username)
        print(password)

        if username == "KivyMD" and password == "kivy":
            self.change_screen("screen2")

    def change_screen(self, screen, *args):
        self.scr_mngr.current = screen


KV = """
#:import Toolbar kivymd.toolbar.Toolbar
#:import ThemeManager kivymd.theming.ThemeManager
#:import MDNavigationDrawer kivymd.navigationdrawer.MDNavigationDrawer
#:import NavigationLayout kivymd.navigationdrawer.NavigationLayout
#:import NavigationDrawerDivider kivymd.navigationdrawer.NavigationDrawerDivider
#:import NavigationDrawerToolbar kivymd.navigationdrawer.NavigationDrawerToolbar
#:import NavigationDrawerSubheader kivymd.navigationdrawer.NavigationDrawerSubheader
#:import MDCheckbox kivymd.selectioncontrols.MDCheckbox
#:import MDSwitch kivymd.selectioncontrols.MDSwitch
#:import MDList kivymd.list.MDList
#:import OneLineListItem kivymd.list.OneLineListItem
#:import TwoLineListItem kivymd.list.TwoLineListItem
#:import ThreeLineListItem kivymd.list.ThreeLineListItem
#:import OneLineAvatarListItem kivymd.list.OneLineAvatarListItem
#:import OneLineIconListItem kivymd.list.OneLineIconListItem
#:import OneLineAvatarIconListItem kivymd.list.OneLineAvatarIconListItem
#:import MDTextField kivymd.textfields.MDTextField
#:import MDSpinner kivymd.spinner.MDSpinner
#:import MDCard kivymd.card.MDCard
#:import MDSeparator kivymd.card.MDSeparator
#:import MDDropdownMenu kivymd.menu.MDDropdownMenu
#:import get_color_from_hex kivy.utils.get_color_from_hex
#:import colors kivymd.color_definitions.colors
#:import SmartTile kivymd.grid.SmartTile
#:import MDSlider kivymd.slider.MDSlider
#:import MDTabbedPanel kivymd.tabs.MDTabbedPanel
#:import MDTab kivymd.tabs.MDTab
#:import MDProgressBar kivymd.progressbar.MDProgressBar
#:import MDAccordion kivymd.accordion.MDAccordion
#:import MDAccordionItem kivymd.accordion.MDAccordionItem
#:import MDAccordionSubItem kivymd.accordion.MDAccordionSubItem
#:import MDThemePicker kivymd.theme_picker.MDThemePicker
#:import MDBottomNavigation kivymd.tabs.MDBottomNavigation
#:import MDBottomNavigationItem kivymd.tabs.MDBottomNavigationItem

#:import partial functools.partial

MyLayout:
    scr_mngr: scr_mngr
    orientation: 'vertical'

    ScreenManager:
        id: scr_mngr
        screen1: screen1

        Screen:
            id: screen1
            name: 'screen1'
            username: username
            password: password

            MDCard:
                size_hint: None, None
                size: dp(520), dp(340)
                pos_hint: {'center_x': 0.5, 'center_y': 0.5}

                BoxLayout:
                    orientation:'vertical'
                    padding: dp(20)
                    spacing:20

                    MDLabel:
                        text: 'Connexion'
                        theme_text_color: 'Secondary'
                        font_style:"Title"
                        size_hint_y: None
                        height: dp(36)

                    MDSeparator:
                        height: dp(1)

                    MDTextField:
                        id: username
                        hint_text: "Username "
                        helper_text_mode: "on_focus"

                    MDTextField:
                        id: password
                        hint_text: "Password "
                        helper_text_mode: "on_focus"
                        password: True

                    MDFlatButton:
                        text: "Connexion"
                        pos_hint: {'center_x': 0.5}
                        on_release: root.check_data_login()
        Screen:
            name: 'screen2'

            Toolbar:
                id: toolbar
                title: "Welcome ! "
                pos_hint: {'center_x': 0.5, 'center_y': 0.97}
                md_bg_color: app.theme_cls.primary_color
                background_palette: 'DeepPurple'
                background_hue: 'A400'
                left_action_items: [['arrow-left', partial(root.change_screen, 'screen1') ]]
                right_action_items: [['animation', lambda x: MDThemePicker().open()]]

            MDLabel:
                font_style: 'Title'
                theme_text_color: 'Primary'
                text: "Data :"
                height: self.texture_size[1] + dp(3)
                halign: 'center'
                pos_hint: {'center_x': 0.5, 'center_y': 0.85}
"""


class MyApp(App):
    title = "Kivy MD Demo"
    theme_cls = ThemeManager()

    def build(self):
        return Builder.load_string(KV)


MyApp().run()
Run Code Online (Sandbox Code Playgroud)

输出

img01 - 输入的用户名和密码 img02 - 显示屏幕 2