首页 > 解决方案 > 使用 lambda 调用带有参数但传递索引而不是项的函数

问题描述

当尝试传递小写字母列表中的当前字母时,它会传递:

当前索引 + 24 * “点击我!”的次数 已被点击

而不仅仅是物品。这是代码。很抱歉,如果没有 Dearpygui,我无法制作它,我不知道如何重新创建它。

# pip install dearpygui
import dearpygui.dearpygui as dpg
import string

dpg.create_context()


def my_func_2(x):
    print(x)


def my_func():
    x = list(string.ascii_lowercase)
    with dpg.window(label="Test window 2"):
        for i in x:
            dpg.add_button(label=i, callback=lambda i=i: my_func_2(i))


with dpg.window(label="Test window"):
    dpg.add_button(label='Click Me!', callback=my_func)

dpg.create_viewport(title='Test')
dpg.setup_dearpygui()
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()

标签: pythonpython-3.xstringlambdadearpygui

解决方案


亲爱的 PyGUI 回调最多可以接收 3 个参数。从文档

Callbacks may have up to 3 arguments in the following order.

sender:
the id of the UI item that submitted the callback

app_data:
occasionally UI items will send their own data (ex. file dialog)

user_data:
any python object you want to send to the function

您需要使用user_data,可以在项目声明中配置。

def my_func():
    x = list(string.ascii_lowercase)
    with dpg.window(label="Test window 2"):
        for i in x:
            dpg.add_button(label=i, callback=lambda s, a, u: my_func_2(u), user_data=i)

推荐阅读