我目前正在撰寫一個測驗機器人,我想出了這個代碼:
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 個按鈕的類。但是它只顯示第三個。我沒有收到任何錯誤。
如何撰寫此代碼才能顯示所有三個?
uj5u.com熱心網友回復:
您需要為每個按鈕使用不同的方法名稱。更改名稱reaction1,reaction2,reaction3將解決你的問題。
原因是ui.button裝飾器不會將按鈕資訊存盤在其他地方,而是將相關資訊附加到方法上并將方法回傳。因此,這三個方法具有相同的名稱,實際上answers.reaction每次定義按鈕時都在重新分配,并且只保留最后一個。discord.py 僅在運行時評估視圖中的所有組件,因此最后一個按鈕是它看到的全部——因此它只顯示最后一個按鈕。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/342631.html
