我正在try 创建一个小型的、可互换的双按钮类,我可以在任何cog中调用它,而不是反复编写相同的代码.除了按钮的标签外,其他一切都正常工作,我无法找到如何从变量中赋值.它被称为opt1self.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

这是否可以修复?如果是这样的话,是否有一种实际的方法可以将变量放入decorator 中,而不必 for each 用例创建单独的类?

推荐答案

解释

您可以使用View.add_item动态添加按钮.这可以在__init__中完成,其中按钮的定义可以访问实例属性.

重要变化:

  • 按钮回调只接受interaction作为参数-您已经可以访问按钮,回调只是一个函数,而不是一个方法(不需要self).

  • 请注意Button的大写字母"B".它是类的构造函数,而不是decorator .

密码

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)

参考

discord.ui.View

discord.ui.Button

Python相关问答推荐

如何将一列中的值与另一列中其之前的所有值进行比较?

如何通过添加索引值来扩展数据框架?

Conda更新在两个版本的fMT之间翻转

七段显示不完整

学习率未更新

错误:找不到TensorFlow / Cygwin的匹配分布

Python中使用Delivercio进行多个请求

Python如何让代码在一个程序中工作而不在其他程序中工作

Ibis中是否有一个ANY或ANY_UTE表达,可以让我比较子查询返回的一组值中的值?

如何获取Django REST框架中序列化器内部的外卡属性?

已删除的构造函数调用另一个构造函数

指示组内的rejected_time是否在creation_timestamp后5分钟内

DataFrame groupby函数从列返回数组而不是值

Python中的嵌套Ruby哈希

为什么带有dropna=False的groupby会阻止后续的MultiIndex.dropna()工作?

如何从具有不同len的列表字典中创建摘要表?

如何使用它?

为什么以这种方式调用pd.ExcelWriter会创建无效的文件格式或扩展名?

Django—cte给出:QuerySet对象没有属性with_cte''''

合并帧,但不按合并键排序