2013-01-15 49 views
1

所以我已经在kivy用户支持(谷歌组)上提问这个问题,但还没有得到任何答复,所以我会在这里尝试。Kivy按钮循环绑定on_press回拨

我有一套基于搜索工具创建的按钮。基本上,它的工作方式是用户在文本输入框中输入搜索词,并根据输入的文本,我的程序在数据库中搜索匹配的结果。如果有匹配的结果,就会创建按钮(将其文本作为匹配结果的文本),这非常有效。但我的问题是,当按钮创建在一个循环中,如何分配他们各自的on_press回叫?例如,在我的情况下,代码看起来是这样的:

在我.kv文件我将TextInput控件:

<my rule>: 
    ti: Ti 
    TextInput: 
     id: Ti 
    on_text: root.function() 

在我.py文件我有以下的(加上一些其他的代码):

t1 = ObjectProperty() 
function(): 
    layout = StackLayout(orientation = 'lr-tb', size_hint = (0.3, 0.8), pos_hint = {'top' : 0.87}) 

    root.clear_widgets() #added this so that upon user input (i.e. on_text event of textinput) only matching results create new buttons 

    list_1 = ['a', 'b', 'c'] #this is a list of matching results 
    root.add_widget(layout) 

    for item in list_1: #this is the loop which creates the buttons 
     buttons = Button(text = str(item), size_hint = (1, 0.1), background_color = [255, 0, 0, 1]) 
     buttons.bind(on_press = self.t1.insert_text(str(item)))     
     layout.add_widget(buttons) 

分配给回调函数的on_press(如上所示)实际上不起作用。它应该完成的是,当用户按下该按钮时,textinput小部件(self.ti1)中的文本应该更改为按钮文本(即按钮可用作自动填充小部件)。我究竟做错了什么? 请注意,以上只是代码的一部分。主代码的结构应该是这样的,唯一的问题在于上面的代码片段。
谢谢!

+0

之前,我问[这个问题](http://stackoverflow.com/questions/13714074/kivy-date-picker-widget)对于填充一个datepicker。我需要指定一个按钮来更改小部件日期的值。诀窍是使用functools模块,特别是partial()函数。 – Horba

回答

2

Bind一个事件类型或属性回调

self.bind(x=my_x_callback, width=my_width_callback,...) 

所以x应该是一个eventproperty,和my_x_callback需要在参照callback/method

my_method有什么区别()和my_method?

让我们做这在控制台上,考虑方法what_up下面的代码::

python<enter> 
Python 2.7.3 (default, Sep 26 2012, 21:51:14) 
[GCC 4.7.2] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> def what_up(): 
...  return 'nothing man, same old stuff' 
... 
>>> print what_up 
<function what_up at 0x7f8df8a76a28> 
>>> print what_up() 
nothing man, same old stuff 

正如你从上述结果看,如果你直接打印what_up你得到裁判的方法,另一方面,如果你调用方法what_up(),你会得到函数返回的任何值,如果不返回任何值,则返回None。

你可以只传递给函数的引用任何变量像::

>>>my_up = what_up 
>>> my_up() 
'nothing man, same old stuff' 
>>> 

在你的代码::

buttons.bind(on_press = self.t1.insert_text(str(item))) 

您调用的函数

on_press = self.t1.insert_text(str(item)) 

而不是通过功能

on_press = partial(self.t1.insert_text, str(item)) 

呼叫from functools import partial