python / kivy编码的初学者。我正在尝试制作一个问题/答案类型的程序。
附加的代码显示了我的问题的简化示例。它以remove_widget/add_widget
交替显示文本输入对话框和一个按钮对话框。
我的问题是,首先,文本输入对话框将焦点放在文本输入上,但是下次出现时,尽管声明了self.gridlayout.txtinput.focus = True
,但它失去了焦点。知道如何保持专注吗?
我尝试添加延迟时间,还尝试在AnswerChoiceScreen的txtinput.focus
中添加on_enter
描述,但没有一个起作用。
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()
<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>:
答案 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_down
(on_press
)事件上有关,但是由于on_touch_up
({{ 1}})事件。因此,使用on_release
可以避免该问题。您可以通过运行原始代码并按下该on_release
按钮来看到这种情况的发生,但不要释放它。在您释放鼠标按钮之前,OK
会一直保持焦点。
您甚至不需要以下行:
TextInput