使用nextcord开发问答机器人时自定义View仅显示第三个按钮如何解决
问题原因
你当前代码的核心问题是3个按钮绑定的异步回调方法全部重名reaction,Python类中定义同名方法时,后定义的会完全覆盖前面的定义,最终只有最后一个绑定了label='3'的按钮被成功注册到View实例中,所以只会显示第三个按钮。
修复方案
需要做两处调整:
- 给三个按钮的回调方法设置不同的名称,避免方法覆盖
- 把回调中硬编码的返回内容替换为初始化传入的
self.ans1/ans2/ans3,否则你初始化传入的答案参数不会生效
修改后的完整代码如下:
class answers(nextcord.ui.View): def __init__(self, ans1, ans2, ans3): super().__init__(timeout=None) self.ans1 = ans1 self.ans2 = ans2 self.ans3 = ans3 self.value = False @nextcord.ui.button(label = '1', custom_id="1", style = nextcord.ButtonStyle.red) async def reaction1(self, button: nextcord.ui.Button, interaction: nextcord.Interaction): await interaction.response.send_message(self.ans1) self.value = True self.stop() @nextcord.ui.button(label='2', custom_id='2' ) async def reaction2(self, button: nextcord.ui.Button, interaction: nextcord.Interaction): await interaction.response.send_message(self.ans2) self.value = True self.stop() @nextcord.ui.button(label='3', custom_id='3') async def reaction3(self, button: nextcord.ui.Button, interaction: nextcord.Interaction): await interaction.response.send_message(self.ans3) self.value = True self.stop()
内容的提问来源于stack exchange,提问作者Thierry Pontavis
相关产品推荐
相关产品推荐

