通过单击动态内联按钮创建处理程序 [英] Creating a handler by clicking on dynamic inline buttons
问题描述
我在数组中动态创建了按钮
I have dynamically created buttons in an array
keyboard = InlineKeyboardMarkup()
keyboard.row_width = 2
for i in range(0, len(adress)):
keyboard.add(InlineKeyboardButton(adress[i].text, callback_data="address_"))
bot.send_message(cid, 'Выберите адрес парковки', reply_markup=keyboard)
如何跟踪其中一个按钮的点击并从中获取文本?我将所有按钮设置为相同的 callback_data.也许你可以这样做 if 调用.data == "address_":
,但是如何获取按钮文本?
How do I track the click of one of the buttons and get the text from it? I set all the buttons the same callback_data. Perhaps you can do this if call. data = = "address_":
, but how do I get the button text?
推荐答案
当用户点击带有 callback_data
的 InlineKeyboardButton
时,会产生一个 CallbackQuery代码>.
CallbackQuery
不包含有关单击的按钮,但仅与按钮具有的 callback_data
相关.因此,如果您想知道与该按钮关联的文本,我建议让每个按钮的 callback_data
都是唯一的.你可以
When a users clicks on an InlineKeyboardButton
with callback_data
, that results in an CallbackQuery
. A CallbackQuery
does not contain info about the text of the button that was clicked, but only about the callback_data
the button had. So if you want to know the text associated with that button I recommend to make the callback_data
unique per button. You could
- 将该文本直接放入
callback_data
- 使
callback_data
成为一些唯一标识符并存储映射标识符 → 文本 - 使
callback_data
成为一些唯一标识符并通过检查callback_query.message.reply_markup.keyboard
中的哪些按钮具有该callback_data
来提取文本>.请注意,这不适用于来自内联消息的回调查询,是那些不带callback_query.message
- put that text directly into the
callback_data
- make the
callback_data
some unique identifier and store a mapping identifier → text - make the
callback_data
some unique identifier and extract the text by checking which of the buttons incallback_query.message.reply_markup.keyboard
has thatcallback_data
. Note that this doesn't work for callback queries from inline messages, is those don't bring along thecallback_query.message
我个人推荐第二种解决方案.
Personally I'd recommand the second solution.
这篇关于通过单击动态内联按钮创建处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!