Python-Kivy编码中的文本输入焦点

时间:2019-08-02 01:53:18

标签: python kivy

python / kivy编码的初学者。我正在尝试制作一个问题/答案类型的程序。

附加的代码显示了我的问题的简化示例。它以remove_widget/add_widget交替显示文本输入对话框和一个按钮对话框。 我的问题是,首先,文本输入对话框将焦点放在文本输入上,但是下次出现时,尽管声明了self.gridlayout.txtinput.focus = True,但它失去了焦点。知道如何保持专注吗?

我尝试添加延迟时间,还尝试在AnswerChoiceScreen的txtinput.focus中添加on_enter描述,但没有一个起作用。

main.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.textinput import TextInput

sm = ScreenManager()
class QALayout1(BoxLayout):
    pass

class QALayout2(BoxLayout):
    pass

class AnswerChoiceScreen(Screen):

    def __init__(self, **kwargs):
        super(AnswerChoiceScreen, self).__init__(**kwargs)
        self.gridlayout = None
        self.gridlayout = QALayout2()
        self.add_widget(self.gridlayout)

    def _create_layout(self):
        if self.gridlayout is not None:
            self.remove_widget(self.gridlayout)
        self.add_widget(self.gridlayout)

    def button1_clicked(self, *args):
        if self.gridlayout is not None:
            self.remove_widget(self.gridlayout)
        self.gridlayout = QALayout2()
        self.add_widget(self.gridlayout)
        self.gridlayout.txtinput.focus = True

    def buttonOK_clicked(self, *args):
        if self.gridlayout is not None:
            self.remove_widget(self.gridlayout)
        self.gridlayout = QALayout1()
        self.add_widget(self.gridlayout)

class myApp(App):
    def build(self):  
        self.anschoi = AnswerChoiceScreen(name = 'anschoi') 
        sm.add_widget(self.anschoi)
        sm.current = 'anschoi'
        return sm

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

my.kv

<AnswerChoiceScreen>:
    BoxLayout:
        orientation: 'vertical'
        padding: 10,40,10,40 
        spacing: 40 

<QALayout1>:
    Button1:
        id: btn1
        text: 'OK'
        on_press: root.parent.button1_clicked()  


<QALayout2>:
    txtinput: txtinput
    orientation: 'vertical'
    TextInput:
        id: txtinput
        text: ''
        multiline: False
        focus: True
    ButtonOK:
        id:ButtonOK
        text: 'OK'
        on_press: root.parent.buttonOK_clicked()  

<Button0@Button>:
<Button1@Button>:
<ButtonOK@Button>:

1 个答案:

答案 0 :(得分:0)

足够奇怪,您要做的就是更改

<QALayout1>:
    Button1:
        id: btn1
        text: 'OK'
        on_press: root.parent.button1_clicked()

收件人:

<QALayout1>:
    Button1:
        id: btn1
        text: 'OK'
        on_release: root.parent.button1_clicked()

on_press更改为on_release。我认为这与您将TextInput的焦点设置在on_touch_downon_press)事件上有关,但是由于on_touch_up({{ 1}})事件。因此,使用on_release可以避免该问题。您可以通过运行原始代码并按下该on_release按钮来看到这种情况的发生,但不要释放它。在您释放鼠标按钮之前,OK会一直保持焦点。

您甚至不需要以下行:

TextInput