多个按钮未显示在 nextcord 中
Multiple Button not showing up in nextcord
我目前正在编写一个测验机器人,我想出了这个代码:
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 reaction(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message('ans1')
self.value = True
self.stop()
@nextcord.ui.button(label='2', custom_id='2' )
async def reaction(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message('ans2')
self.value = True
self.stop()
@nextcord.ui.button(label='3', custom_id='3')
async def reaction(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message('ans3')
self.value = True
self.stop()
这是应该显示 3 个按钮的 class。但是它只显示第三个。我没有收到任何错误。
我如何编写这段代码才能显示所有三个?
您需要为每个按钮使用不同的方法名称。将名称更改为 reaction1
、reaction2
、reaction3
将解决您的问题。
原因是 ui.button
装饰器没有将按钮信息存储在别处,而是将相关信息附加到方法上,然后 returns 返回方法。因此,这三个方法具有相同的名称,实际上每次定义按钮时都会重新分配 answers.reaction
,并且只保留最后一个。 discord.py 仅在运行时评估视图中的所有组件,因此它只看到最后一个按钮 - 因此它仅显示最后一个按钮。
我目前正在编写一个测验机器人,我想出了这个代码:
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 reaction(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message('ans1')
self.value = True
self.stop()
@nextcord.ui.button(label='2', custom_id='2' )
async def reaction(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message('ans2')
self.value = True
self.stop()
@nextcord.ui.button(label='3', custom_id='3')
async def reaction(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message('ans3')
self.value = True
self.stop()
这是应该显示 3 个按钮的 class。但是它只显示第三个。我没有收到任何错误。
我如何编写这段代码才能显示所有三个?
您需要为每个按钮使用不同的方法名称。将名称更改为 reaction1
、reaction2
、reaction3
将解决您的问题。
原因是 ui.button
装饰器没有将按钮信息存储在别处,而是将相关信息附加到方法上,然后 returns 返回方法。因此,这三个方法具有相同的名称,实际上每次定义按钮时都会重新分配 answers.reaction
,并且只保留最后一个。 discord.py 仅在运行时评估视图中的所有组件,因此它只看到最后一个按钮 - 因此它仅显示最后一个按钮。