EN VI

Python - can not pass local variable into button decorator?

2024-03-09 23:00:21
Python - can not pass local variable into button decorator

How do I pass the self.canCraft variable into the decorator? I understand the problem why it doesn't work, but I cant find a solution. I dont want to do it with a global variable.

class CraftView(discord.ui.View):
    def __init__(self, viewOwner, craftItem, canCraft):
        super().__init__()
        self.viewOwner = viewOwner
        self.craftItem = craftItem
        self.canCraft = canCraft

    @discord.ui.button(label="Craft", style=discord.ButtonStyle.primary, emoji="🔨", disabled=self.canCraft)
    async def button_callback(self, interaction: Interaction, button: ui.Button):
        pass

Solution:

You're probably better off subclassing discord.ui.Button and adding it to a view like so-

import discord

class CraftButton(discord.ui.Button):
    def __init__(self, label:str, emoji:str, disabled:bool, style:discord.ButtonStyle=discord.ButtonStyle.primary):
        super().__init__(label=label, emoji=emoji, disabled=disabled, style=style)

    async def callback(interaction:discord.Interaction):
        ...

class CraftView(discord.ui.View):
    def __init__(self, view_owner, craft_item, can_craft):
        super().__init__()
        self.view_owner = view_owner
        self.craft_item = craft_item
        self.add_item(CraftButton("Craft", "🔨", can_craft))
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login