【问题标题】:Python - Kivy: KeyError with Text Input using ScreenManagerPython - Kivy:使用 ScreenManager 进行文本输入的 KeyError
【发布时间】:2021-09-12 21:32:12
【问题描述】:

我正在使用 KivyScreenManager(以及 KivyMD)进行一个项目。

使用它的原因是我需要制作一个具有多个屏幕的应用程序。我的目标是通过 (a string) ID 然后 从现有的 MDTextField 中获取 User Input打印出来

但是,我不断收到此错误File "<string>", line 37, in <module> File "c:/Users/admin/Desktop/myApp/Main.py", line 75, in loginFunction username = mainScreenInstance.ids["input_username"].text KeyError: 'input_username'

我已经在整个互联网和 StackOverflow 上搜索了答案,但似乎没有任何解决方案适合我。也许有人可以帮助我解决我的问题并使我的代码正常工作。

无论如何,这是我简短的代码

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

screen_helper = """
ScreenManager: 
    MenuScreen:
        name: 'menu'
    SecondScreen:
        name: 'second'

<MenuScreen>:
    MDToolbar:
        title: "Menu Screen"
        pos_hint: {"top": 1}
        anchor_title: "center"
        md_bg_color: (0/255, 0/255, 0/255, 1)
    Image:
        source: "Logo_h_black.png"
        pos_hint: {"center_x": 0.5, "center_y": 0.75}
        size_hint_x: (0.25)
        size_hint_y: (0.25)
    MDTextField:
        id: input_username
        hint_text: "Username"
        size_hint: (0.5, 0.1)
        pos_hint: {"center_x": 0.5, "center_y": 0.55}
        font_size: 20
        mode: "rectangle"
    MDTextField:
        id: input_password
        hint_text: "Password"
        size_hint: (0.5, 0.1)
        pos_hint: {"center_x": 0.5, "center_y": 0.45}
        font_size: 20
        mode: "rectangle"
    MDFillRoundFlatButton:
        text: "LOG IN"
        font_size: 17
        pos_hint: {"center_x": 0.5, "center_y": 0.25}
        on_press: app.loginFunction()
    
<SecondScreen>:
    MDLabel:
        text: 'Profile'
        halign: 'center'
    MDRectangleFlatButton:
        text: 'Back'
        pos_hint: {'center_x':0.5,'center_y':0.1}
        on_press: root.manager.current = 'menu'
        

"""

class MenuScreen(Screen):
    pass

class SecondScreen(Screen):
    pass

sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(SecondScreen(name='second'))


class myApp(MDApp):

    def loginFunction(self, args=None):          
                                                 
        if args is None:
           args = sys.argv

        mainScreenInstance = sm.get_screen('menu')

        username = mainScreenInstance.ids["input_username"].text
        password = mainScreenInstance.ids["input_password"].text

        print (username)
        print (password)

    def build(self):
        screen = Builder.load_string(screen_helper)
        return screen

myApp().run()

【问题讨论】:

    标签: python kivy user-input keyerror


    【解决方案1】:

    问题是您的loginFunction 试图从sm 获取mainScreenInstance,但sm 是在screen_helper 加载之前创建的,因此它不知道您的ids已在您的screen_helper 中定义。此外,sm 实际上并未用作 GUI 的一部分,它只是被忽略(除了您在 loginFunction 中对它的引用)。

    因此,我建议您完全消除以下几行:

    sm = ScreenManager()
    sm.add_widget(MenuScreen(name='menu'))
    sm.add_widget(SecondScreen(name='second'))
    

    并通过替换将loginFunction 更改为不使用sm

    mainScreenInstance = sm.get_screen('menu')
    

    与:

    mainScreenInstance = self.root.get_screen('menu')
    

    【讨论】:

      【解决方案2】:

      您正在复制小部件定义,然后没有在代码中使用它们。最后,您将使用新实例从 screen_helper 字符串覆盖屏幕管理器。当我开始学习 Kivy 时,我做了一些。 kv 语言起初令人困惑,但一旦你掌握它就很漂亮。这个版本应该可以工作(我没有测试过它,因为我还没有找到在我手机的开发环境中安装 kivymd 的简单方法):

      from kivymd.app import MDApp
      from kivy.lang.builder import Builder
      from kivy.uix.screenmanager import Screen
      import sys
      
      screen_helper = """
      ScreenManager:
          MenuScreen:
              name: 'menu'
          SecondScreen:
              name: 'second'
      
      <MenuScreen>:
          MDToolbar:
              title: "Menu Screen"
              pos_hint: {"top": 1}
              anchor_title: "center"
              md_bg_color: (0, 0, 0, 1)
          Image:
              source: "Logo_h_black.png"
              pos_hint: {"center_x": 0.5, "center_y": 0.75}
              size_hint_x: (0.25)
              size_hint_y: (0.25)
          MDTextField:
              id: input_username
              hint_text: "Username"
              size_hint: (0.5, 0.1)
              pos_hint: {"center_x": 0.5, "center_y": 0.55}
              font_size: 20
              mode: "rectangle"
          MDTextField:
              id: input_password
              hint_text: "Password"
              size_hint: (0.5, 0.1)
              pos_hint: {"center_x": 0.5, "center_y": 0.45}
              font_size: 20
              mode: "rectangle"
          MDFillRoundFlatButton:
              text: "LOG IN"
              font_size: 17
              pos_hint: {"center_x": 0.5, "center_y": 0.25}
              on_press: app.loginFunction()
          
      <SecondScreen>:
          MDLabel:
              text: 'Profile'
              halign: 'center'
          MDRectangleFlatButton:
              text: 'Back'
              pos_hint: {'center_x':0.5,'center_y':0.1}
              on_press: root.manager.current = 'menu'
              
      
      """
      
      class MenuScreen(Screen):
          pass
      
      class SecondScreen(Screen):
          pass
      
      
      class myApp(MDApp):
          sm = None
          def on_start():
              self.sm = self.root
      
          def loginFunction(self, args=None):                       
              if args is None:
                 args = sys.argv
      
              mainScreenInstance = self.sm.get_screen('menu')
      
              username = mainScreenInstance.ids["input_username"].text
              password = mainScreenInstance.ids["input_password"].text
      
              print (username)
              print (password)
      
              # if self.is_login_correct(username, password):
              #     self.sm.current('second') 
      
          def build(self):
              return Builder.load_string(screen_helper) 
      
      myApp().run()
      

      就个人而言,为了保持一致性,我会将所有与登录相关的功能移至 MenuScreen 类。

      【讨论】:

        猜你喜欢
        • 2021-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-01
        • 1970-01-01
        相关资源
        最近更新 更多