python - 使用 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()
解决方案
亲爱的 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)
推荐阅读
- python - 我正在使用 python selenium 从 html 页面抓取“href”。但我正面临这个握手错误
- php - 根据 WooCommerce 产品重量替换添加到购物车按钮
- php - octobercms 无法连接到数据库;.env 很好,php artisan tinker / echo env('DB_*') 输出正确的内容
- ios - 如何在 CKRecords 结果 Xcode Objective-c 中分离出字段
- flutter - 获取应用程序缓存大小颤动
- postgresql - 使用 sequelize 连接 Postgresql 数据库
- delphi - 为什么类型名称_Recordset 中有下划线?
- ios - 快速从url下载pdf并将其保存到文件中
- math - 分解 99 位长的大素数的问题
- java - Google Tink 混合参数