PythonKivy编码中的文本输入焦点

2024-06-23 19:18:06 发布

您现在位置:Python中文网/ 问答频道 /正文

python/kivy编码初学者。我想做一个问答式的节目。你知道吗

附加的代码显示了我的问题的一个简化的例子。它通过remove_widget/add_widget交替显示文本输入对话框和一键对话框。 我的问题是,一开始,文本输入对话框在文本输入中有焦点,但下次出现时,它会失去焦点,尽管它声明了self.gridlayout.txtinput.focus = True。你知道我怎样才能保持它的焦点吗?你知道吗

我试着添加延迟时间,也试着在AnswerChoiceScreen的on_enter中添加txtinput.focus描述,但都没有效果。你知道吗

你知道吗主.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>:

Tags: fromimportselfadddefwidgetremovefocus
1条回答
网友
1楼 · 发布于 2024-06-23 19:18:06

奇怪的是,你需要做的就是改变

<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_upon_release)事件,它失去了焦点。所以使用on_release可以避免这个问题。您可以通过运行原始代码并按下OK按钮看到这种情况,但不要释放它。TextInput将具有焦点,直到您释放鼠标按钮。你知道吗

你甚至不需要排队:

self.gridlayout.txtinput.focus = True

相关问题 更多 >

    热门问题