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

如何在Python Pycord中重置Discord.OptionSelect?解决返回按钮报错

问题解决:Pycord下拉菜单重复选项报错

错误原因

报错In components.0.components.0.options.1: The specified option value is already used的核心原因:

  • 全局变量options被反复追加选项,每次进入分类都会往列表里添加相同的选项,第二次进入同一分类时,下拉菜单出现重复选项,触发Discord API的重复值校验规则。
  • @discord.ui.select装饰器的options参数在类定义阶段就已绑定,不会随全局变量的更新动态刷新,进一步导致重复选项累积。

解决方案

删除全局变量,在CategoryPriceView初始化时动态生成当前分类的选项列表,并手动创建select组件添加到视图中,确保每次实例化都使用独立的选项集合。

修改后的代码

example2.py

import discord

class CategoryPriceView(discord.ui.View):
    def __init__(self, category, father):
        super().__init__()
        self.category = category
        self.father = father

        # 动态生成当前分类对应的选项
        category_options = []
        if self.category == 'Meats':
            category_options.append(discord.SelectOption(label='Steak', description="Price: 40$"))
        elif self.category == 'Salads':
            category_options.append(discord.SelectOption(label='Greek Salad', description="Price: 30$"))

        # 手动创建select组件并绑定回调函数
        self.item_select = discord.ui.Select(
            placeholder="Choose an item!",
            min_values=1,
            max_values=1,
            options=category_options
        )
        self.item_select.callback = self.select_callback
        self.add_item(self.item_select)

    @discord.ui.button(label="Back", row=1, style=discord.ButtonStyle.blurple) 
    async def button_callback(self, button, interaction):
        await interaction.response.edit_message(content="Choose a category from the dropdown below! ✨", view=self.father)

    async def select_callback(self, select, interaction):
        item = select.values[0]
        await interaction.response.edit_message(content=f"You chose {item}! ", view=None) 

说明

修改后,每次创建CategoryPriceView实例时都会生成全新的选项列表,彻底避免重复选项问题。同时手动创建select组件的方式,规避了装饰器静态绑定的限制,确保每个视图实例的下拉菜单都对应正确的分类选项。

内容的提问来源于stack exchange,提问作者yarin Cohen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:25:17