You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py开发中如何使用discord-components库修改Button组件属性

discord-components库Button.set_disabled()使用指南

set_disabled()是discord-components库提供的按钮状态修改专用方法,修改后需要重新更新消息组件才能在前端生效,具体使用规则和落地示例如下:

  • 基础语法:按钮实例.set_disabled(布尔值),传入True禁用按钮,传入False启用按钮
  • 注意:仅调用方法修改按钮属性不会自动同步到Discord客户端,必须将修改后的组件完整传入消息编辑接口的components参数,才会触发生效

基础使用示例

from discord_components import Button, DiscordComponents
import discord

# 初始化客户端和组件库
client = discord.Client(intents=discord.Intents.all())
DiscordComponents(client)

# 初始化测试按钮
test_btn = Button(label="点击测试", custom_id="test_btn", style=1)

@client.event
async def on_message(message):
    if message.content == "!发送按钮":
        await message.channel.send("测试消息", components=[test_btn])

@client.event
async def on_button_click(interaction):
    if interaction.custom_id == "test_btn":
        # 调用set_disabled禁用按钮
        test_btn.set_disabled(True)
        # 重新传递components参数更新消息
        await interaction.edit_original_message(components=[test_btn])
        await interaction.respond(content="按钮已被禁用")

client.run("你的机器人令牌")

井字棋场景适配示例

针对你要开发的井字棋游戏,可通过全局维护3x3按钮数组的方式实现落子后禁用对应位置:

# 初始化3行3列的井字棋按钮组
tic_buttons = [
    [Button(label=" ", custom_id=f"tic_0_0"), Button(label=" ", custom_id=f"tic_0_1"), Button(label=" ", custom_id=f"tic_0_2")],
    [Button(label=" ", custom_id=f"tic_1_0"), Button(label=" ", custom_id=f"tic_1_1"), Button(label=" ", custom_id=f"tic_1_2")],
    [Button(label=" ", custom_id=f"tic_2_0"), Button(label=" ", custom_id=f"tic_2_1"), Button(label=" ", custom_id=f"tic_2_2")]
]
# 标记当前落子玩家,True为X,False为O
current_x_turn = True

@client.event
async def on_button_click(interaction):
    if not interaction.custom_id.startswith("tic_"):
        return
    # 解析点击的按钮行列坐标
    _, row, col = interaction.custom_id.split("_")
    row, col = int(row), int(col)
    target_btn = tic_buttons[row][col]
    # 修改按钮状态和标签
    target_btn.set_disabled(True)
    target_btn.label = "X" if current_x_turn else "O"
    # 切换玩家
    global current_x_turn
    current_x_turn = not current_x_turn
    # 更新消息组件
    await interaction.edit_original_message(components=tic_buttons)
    # 后续可补充胜负判定、平局判定逻辑

常见踩坑说明

  • 如果按钮嵌套在ActionRow容器中,修改按钮后需要将完整的ActionRow数组传递给components参数,不能只传单个按钮
  • 不要每次触发事件都重新初始化按钮实例,直接修改全局维护的实例属性即可,避免custom_id冲突
  • 按钮的style、label等其他属性修改后也需要遵循同样的更新规则,重新传递components参数生效

内容的提问来源于stack exchange,提问作者EricPlayz YT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 11:06:01