2013-01-15 55 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