【发布时间】:2019-08-02 01:53:18
【问题描述】:
python/kivy 编码的初学者。我正在尝试制作一个问题/答案类型的程序。
附加代码显示了我的问题的简化示例。它以remove_widget/add_widget 交替显示文本输入对话框和一键对话框。
我的问题是,起初,文本输入对话框在文本输入中具有焦点,但下一次出现时,它失去了焦点,尽管声明了self.gridlayout.txtinput.focus = True。知道如何保持专注吗?
我尝试添加延迟时间,也尝试在 AnswerChoiceScreen 的 on_enter 中添加 txtinput.focus 描述,但均无效。
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()
我的.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>:
【问题讨论】:
-
为什么不使用 self.gridlayout.ids["textinput"]
-
只是因为 Kivy 参考手册建议使用 PropertyObjects 而不是 ids 库解决方案。