【发布时间】:2016-04-26 03:33:51
【问题描述】:
我正在使用 kivy 创建一个应用程序。所以我认为我没有正确理解 FloatInput 的 on_focus 行为。
让我先描述一下我想在这里做什么。当用户单击 TextInput 时,我试图激活一个弹出小键盘(这个小键盘只有数字 0-9 的按钮和一个“输入”按钮)。接下来,一旦用户在弹出小键盘中输入数字并点击“输入”按钮,弹出窗口应该关闭并且 TextInput 的文本字段应该更新为用户输入的数字。
但是,我遇到了问题。本质上,我有一个包含多个如上所述构造的 TextInput 的表单(我将在下文中将它们称为“FloatInputs”b/c,这就是我给它们命名的)。我第一次将值输入其中一个 FloatInputs 时,一切都按预期工作。但是每当我尝试在第二个 FloatInput 中输入一个数字时,就会出现问题。具体来说,on_focus 函数被调用了两次,结果用户必须在弹出窗口中输入两次值(这显然不理想,因为它会使用户感到沮丧)。
如果这是一个愚蠢的问题,我深表歉意,但我已经对此感到困惑了很长一段时间。我认为问题的核心在于 TextInput 和弹出小部件的聚焦顺序,但我在这里可能错了。如果有人可以就如何修复此错误提供建议,我将不胜感激。
这里是相关的python代码:
class FloatInput(TextInput):
def on_focus(self, instance, value):
print 'ON FOCUS CALLED - THIS SHOULD ONLY BE CALLED ONCE!'
# Adding this helped part of the problem (however, on_focus is still being called twice???)
self.unfocus_on_touch = False
prompt_content = BoxLayout(orientation='vertical') # Main layout
num_pad = NumPadWidget()
prompt_content.add_widget(num_pad)
def my_callback(instance):
self.text = num_pad.ids.num_label.text
self.popup.dismiss()
# Now define the popup, with the content being the layout:
self.popup = Popup(id='num_pad_popup', title='Enter value', content=prompt_content, size_hint=(0.8,0.5), autodismiss=False)
num_pad.ids.enter_btn.bind(on_press=my_callback)
# Open the pop-up:
self.popup.open()
这里是相关的kv代码:
<NumPadButton@Button>:
font_size: '16dp'
bold: True
<NumPadWidget>:
BoxLayout:
orientation: 'vertical'
BoxLayout:
size_hint_y: 1
id: num_label
Label:
id: num_label
text: ''
BoxLayout:
size_hint_y: 5
orientation: 'vertical'
BoxLayout:
NumPadButton:
text: '7'
on_press:
num_label.text = num_label.text + '7'
NumPadButton:
text: '8'
on_press:
num_label.text = num_label.text + '8'
NumPadButton:
text: '9'
on_press:
num_label.text = num_label.text + '9'
BoxLayout:
NumPadButton:
text: '4'
on_press:
num_label.text = num_label.text + '4'
NumPadButton:
text: '5'
on_press:
num_label.text = num_label.text + '5'
NumPadButton:
text: '6'
on_press:
num_label.text = num_label.text + '6'
BoxLayout:
NumPadButton:
text: '1'
on_press:
num_label.text = num_label.text + '1'
NumPadButton:
text: '2'
on_press:
num_label.text = num_label.text + '2'
NumPadButton:
text: '3'
on_press:
num_label.text = num_label.text + '3'
BoxLayout:
NumPadButton:
text: '0'
on_press:
num_label.text = num_label.text + '0'
NumPadButton:
text: '.'
on_press:
num_label.text = num_label.text + '.'
NumPadButton:
text: 'del'
on_press:
num_label.text = num_label.text[:-1]
BoxLayout:
BoxLayout:
size_hint_x: 1
NumPadButton:
text: 'C'
on_press:
num_label.text = ''
BoxLayout:
size_hint_x: 2
NumPadButton:
id: enter_btn
text: 'Enter'
【问题讨论】:
-
第一句应该以 TextInput 而不是 FloatInput 结尾。对于造成的混乱,我深表歉意。