如何在 kivymd focus agane 中制作输入字段

How to Make Input Field in kivymd focus agane

使用 kivymd 尽可能快速地制作扫描条形码的应用程序,我创建了这个应用程序,其中包含一个文本字段,该文本字段将获取 QR 码并存储它,如果用户输入一次,焦点就会消失,必须手动将其聚焦才能获得另一个来自用户的输入。有可能让它在不失去注意力的情况下接受很多输入吗?

main.py

from kivymd.app import MDApp
from kivymd.uix.screen import Screen



class Layout(Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
    
    def check(self):
        item = self.ids.qrcode
        print(item.text)
       
        


class Core(MDApp):
    def build(self):
        self.theme_cls.primary_palette = "Green"
        return Layout()

if __name__ == '__main__':
    Core().run()

core.kv

<Layout>:
    cols:1
    MDTextField:
        id: qrcode
        hint_text: "QR Code"
        focus: True
        helper_text: "Enter Shipment QR"
        helper_text_mode: "on_focus"
        icon_right: "qrcode-scan"
        icon_right_color: app.theme_cls.primary_color
        pos_hint:{'center_x': 0.5, 'center_y': 0.9}
        size_hint_x:None
        width:300
        on_text_validate: root.check()

如果将 self.ids.qrcode.focus = True 放在 check 方法中,它会被过早调用。你会集中注意力,然后就会失去焦点。

您可以通过以下方法在 check 方法中使用 Clock.schedule_once(self.refocus_ti)

def refocus_ti(self, *args):
    self.ids.qrcode.focus = True

使用上面的代码,它将在您的 check 方法之后重新聚焦文本字段。

完整的代码片段:

# core.kv
<Layout>:
    cols:1
    qrTextInput: qrcode
    MDTextField:
        id: qrcode
        hint_text: "QR Code"
        focus: True
        helper_text: "Enter Shipment QR"
        helper_text_mode: "on_focus"
        icon_right: "qrcode-scan"
        icon_right_color: app.theme_cls.primary_color
        pos_hint:{'center_x': 0.5, 'center_y': 0.9}
        size_hint_x:None
        width:300
        on_text_validate: root.check()
from kivymd.app import MDApp
from kivymd.uix.screen import Screen
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.clock import Clock

Builder.load_file("kv/core.kv")

class Layout(Screen):
    qrTextInput = ObjectProperty(None)
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
    
    def check(self):
        item = self.ids.qrcode # Or access with self.qrTextInput.text
        print(item.text)        
        Clock.schedule_once(self.refocus_ti)

    def refocus_ti(self, *args):
        self.qrTextInput.focus = True


class Core(MDApp):
    def build(self):
        self.theme_cls.primary_palette = "Green"
        return Layout()

if __name__ == '__main__':
    Core().run()