Pycord自定义View传参报错'children'不存在,按钮不渲染求助
问题解决方法
核心原因
你的MyView类重写了__init__方法,但没有调用父类discord.ui.View的构造函数,导致父类负责初始化的children属性缺失,这是按钮无法渲染、报错的直接原因。
修复步骤及代码调整
- 调用父类构造函数:在
MyView的__init__中添加super().__init__(),确保父类的必要属性被初始化。可按需设置timeout(比如timeout=None让View永久有效)。 - 修正按钮禁用属性:按钮禁用的正确属性是
disabled,而非disable。 - 修正实例方法调用:
video_finder是实例方法,需用self.video_finder()调用,不能直接通过类调用MyView.video_finder()。 - 补充缺失方法:你的代码中未定义
video_finder方法,需补充实现(否则会触发新的报错)。
修复后的完整代码
class MyView(discord.ui.View): def __init__(self, link): # 调用父类构造函数,初始化children等核心属性 super().__init__(timeout=None) self.link = link # 补充实现video_finder方法,根据需求编写下载逻辑 async def video_finder(self): # 使用self.link获取传入的视频链接,执行下载操作 pass @discord.ui.button(label='480p', style=discord.ButtonStyle.gray, emoji='🎥') async def button_callback_480(self, button, interaction): button.disabled = True await self.video_finder() await interaction.response.send_message('downloading the file. Check the server for file') await interaction.followup.send('follow up added to the queue') # 更新消息的View,让按钮禁用状态生效 await interaction.message.edit(view=self) @discord.ui.button(label='720p', style=discord.ButtonStyle.danger, emoji='🎥') async def button_callback_720(self, button, interaction): button.disabled = True # 若720p也需调用下载逻辑,取消下方注释 # await self.video_finder() await interaction.response.send_message('downloading the file. Check the server for file') await interaction.followup.send('follow up added to the queue') await interaction.message.edit(view=self) # 斜杠命令无需修改 @bot.command(description="Choose the quality of video you want to download") async def ytdl(ctx, link: str): view = MyView(link) await ctx.respond('Choose the quality of video you want to download', view=view)
额外说明
- 调用
interaction.message.edit(view=self)是为了让按钮的禁用状态实时同步到消息上,用户能直观看到按钮状态变化。 - 如果不需要View永久生效,可将
timeout设为具体秒数,比如super().__init__(timeout=300)表示5分钟后View自动失效。
内容的提问来源于stack exchange,提问作者Siddhant Ota
相关产品推荐
相关产品推荐

