所以我已經在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)中的文本應該更改爲按鈕文本(即按鈕可用作自動填充小部件)。我究竟做錯了什麼? 請注意,以上只是代碼的一部分。主代碼的結構應該是這樣的,唯一的問題在於上面的代碼片段。
謝謝!
之前,我問[這個問題](http://stackoverflow.com/questions/13714074/kivy-date-picker-widget)對於填充一個datepicker。我需要指定一個按鈕來更改小部件日期的值。訣竅是使用functools模塊,特別是partial()函數。 – Horba