Kivy按钮循环绑定(bind)on_press回调

标签 kivy

所以我在 kivy 用户支持(谷歌群组)上问了这个问题,但还没有得到任何回复,所以我会在这里尝试一下。

我有一组基于搜索工具创建的按钮。基本上,它的工作方式是用户在文本输入框中输入搜索词,然后根据输入文本,我的程序在数据库中搜索匹配的结果。如果有任何匹配的结果,则会创建按钮(其文本作为匹配结果的文本),这非常有效。但我的问题是,当在循环中创建按钮时,如何将其各自的 on_press 分配给回调?例如,在我的例子中,代码如下所示:

在我的 .kv 文件中,我有文本输入小部件:

<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(如上所示)实际上不起作用。它应该完成的是,当用户按下该按钮时,文本输入小部件(self.ti1)中的文本应该更改为按钮文本(即按钮作为自动填充小部件)。我究竟做错了什么? 注意,上面只是部分代码。主要代码的结构应该如此,唯一的问题在于上面的代码片段。
谢谢!

最佳答案

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 importpart

关于Kivy按钮循环绑定(bind)on_press回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14329174/

相关文章:

mysql - 使用 Kivy 检索 MySQL

python - Kivy 中的分屏?

python - 无法从 kivy 对象获取 id

python 基维 : how to use filechooser access files outside C drive

python - Kivy - 屏幕管理器 - 访问其他类中的属性

python - 删除 kivy 图中的图

python - kivy,如何通过文本更改触发事件

python - 导入错误 : No module named kivy

python - 使用 pyinstaller 生成的基于 kivy 的 Windows exe 黑屏

python - 如何将Python变量获取到Kivy?