我正在尝试制作一个小型的、可互换的两按钮类,我可以在任何齿轮中调用它,而不是一遍又一遍地编写相同的代码。除了按钮标签之外,一切都工作正常,我无法找到如何从变量中分配标签。称为 asopt1或self.opt1,它失败了,因为两者在技术上都不是“定义”的,我确实理解,但我似乎找不到任何替代方案。
该类的片段如下:
class twoButton(discord.ui.View):
def __init__(self, author, opt1="Yes", opt2="No", timeout=0):
self.author = author
self.opt1 = opt1
self.opt2 = opt2
super().__init__(timeout=timeout)
@discord.ui.button(label=opt1, style=discord.ButtonStyle.blurple, custom_id="opt1")
async def buttonOne(self, interaction: discord.Interaction, button: discord.ui.Button):
button.style = discord.ButtonStyle.green
self.buttonTwo.style = discord.ButtonStyle.gray
await interaction.response.edit_message(view=self)
@discord.ui.button(label=opt2, style=discord.ButtonStyle.blurple, custom_id="opt2")
async def buttonTwo(self, interaction: discord.Interaction, button: discord.ui.Button):
button.style = discord.ButtonStyle.green
self.buttonOne.style = discord.ButtonStyle.gray
await interaction.response.edit_message(view=self)
async def interaction_check(self, interaction: discord.Interaction):
return interaction.user.id == self.author.id
Run Code Online (Sandbox Code Playgroud)
这可以修复吗?如果是这样,是否有一种实际方法可以将变量放入装饰器中,而无需为每个用例创建单独的类?
您可以使用 动态添加按钮View.add_item。这可以在 中完成__init__,其中按钮的定义可以访问实例属性。
重要变化:
按钮回调仅interaction作为参数 - 您已经可以访问按钮,并且回调只是一个函数,而不是方法(不需要self)。
请注意 的大写“B” Button。它是类的构造函数,而不是装饰器。
class TestView(discord.ui.View):
def __init__(self, example_var):
self.example_var = example_var
super().__init__(timeout=None)
self.add_buttons()
def add_buttons(self):
button_one = discord.ui.Button(label=self.example_var)
async def button_example(interaction: discord.Interaction):
print(self.example_var)
button_one.callback = button_example
self.add_item(button_one)
Run Code Online (Sandbox Code Playgroud)