Discord.py 1.7.3中discord_components按钮无法并排显示问题
问题根因
按钮纵向排列的核心原因有两个:
- 代码漏了
discord_components的初始化步骤,组件客户端未启动会导致组件渲染逻辑异常 components参数传参格式错误:该参数要求传入组件行列表,直接传入单个ActionRow对象时,库会把ActionRow内的每个按钮单独解析为独立行,最终呈现纵向排列效果
修复步骤
- 在机器人实例初始化完成后,添加组件客户端初始化代码:
DiscordComponents(bot) - 调整
components参数的传值结构:把构造的ActionRow实例放到列表中传入,或直接用嵌套列表结构声明同行组件,库会自动将同个内层列表内的组件识别为同一行横向排列
修复后完整代码
import discord from discord.ext import commands import random import time from discord_components import * bot = commands.Bot(command_prefix="!") # 初始化组件客户端,缺少这行组件功能无法正常工作 DiscordComponents(bot) @bot.command() async def test(ctx): button = Button( style=ButtonStyle.blue, custom_id="primary", label="Blue button", ) button2 = Button( style=ButtonStyle.red, custom_id="secondary", label="Red button", ) action_row = ActionRow(components=[button, button2]) # components参数需传入包含ActionRow的列表,而非直接传入ActionRow对象 await ctx.send("Hello World!", components=[action_row])
简化写法参考
不需要手动构造ActionRow对象,直接用嵌套列表传参即可,库会自动完成行包装,效果和手动构造ActionRow完全一致:
# 外层列表每个元素代表一行,内层列表存放同一行的组件 await ctx.send("Hello World!", components=[[button, button2]])
补充说明:Discord限制单个ActionRow最多放置5个按钮,超出数量的按钮会被自动换行,当前示例的2个按钮完全符合规则,不会触发自动换行。如果需要实现多行按钮,在外层列表追加多个内层组件列表即可。
内容的提问来源于stack exchange,提问作者WolfClawsKevin
相关产品推荐
相关产品推荐

