【问题标题】:Using lambda to call a function with an argument but passing index rather than item使用 lambda 调用带有参数但传递索引而不是项的函数
【发布时间】:2021-10-18 03:23:13
【问题描述】:

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

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

而不仅仅是物品。这是代码。很抱歉没有dearpygui就无法制作它,没有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()

【问题讨论】:

    标签: python python-3.x string lambda dearpygui


    【解决方案1】:

    亲爱的 PyGUI 回调最多可以接收 3 个参数。来自docs

    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)
    

    【讨论】:

      猜你喜欢
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      相关资源
      最近更新 更多