我对Python并不是太陌生,但对它也不是很有经验,我不确定如何使用不一致按钮和类来做到这一点.我已经知道如何使用react ,但我认为按钮更好.

我已经try 了很多添加按钮的方法,按钮确实被添加了,但是点击它们并不能得到我想要的响应.

我的代码:

@bot.command()
async def button(ctx):
  pages=["page1","page2","page3","page4"]
  button1=Button(label="<",style=discord.ButtonStyle.green)
  button2=Button(label=">",style=discord.ButtonStyle.green)
  page=0
  async def button1_callback(interaction):
    if page>0:
      return await interaction.response.edit_message(content=pages[page-1])
      page-=1
    else:
      return
  async def button2_callback(interaction):
    if page<len(pages)-1:
      return await interaction.response.edit_message(content=pages[page+1])
      page+=1
    else:
      return
  button1.callback= button1_callback
  button2.callback= button2_callback
  view=View()
  view.add_item(button1)
  view.add_item(button2)
  await ctx.send(pages[page],view=view)

我想要它,这样点击前进的箭头加1和发送页面2,3等和后退箭头反过来.

推荐答案

回调函数中的page变量没有引用您在button函数中定义的page变量.让我们try 使用nonlocal来确保回调函数引用正确的page变量.

编辑:修改了我在Łukasz Kwieciński的注释上的代码,代码将在函数外部定义,我们将页面作为参数传递给类的构造函数,并使页面变量成为实例变量

from discord.ui import Button, View
from discord import ButtonStyle

class PaginationView(View):
    def __init__(self, pages):
        super().__init__()
        self.page = 0
        self.pages = pages

        self.add_item(Button(label="<", style=ButtonStyle.green, custom_id="prev"))
        self.add_item(Button(label=">", style=ButtonStyle.green, custom_id="next"))

    @discord.ui.button(custom_id="prev")
    async def prev_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        if self.page > 0:
            self.page -= 1
            await interaction.response.edit_message(content=self.pages[self.page])

    @discord.ui.button(custom_id="next")
    async def next_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        if self.page < len(self.pages) - 1:
            self.page += 1
            await interaction.response.edit_message(content=self.pages[self.page])

@bot.command()
async def button(ctx):
    pages = ["page1","page2","page3","page4"]
    await ctx.send(pages[0], view=PaginationView(pages))

Python相关问答推荐

判断两极中N(N 2)列水平是否相等

回归回溯-2D数组中的单词搜索

收件箱转换错误- polars.exceptions. ComputeHelp- pandera(0.19.0b3)带有polars

DuckDB将蜂巢分区插入拼花文件

Polars:使用列值引用when / then表达中的其他列

Python 3.12中的通用[T]类方法隐式类型检索

为什么tkinter框架没有被隐藏?

C#使用程序从Python中执行Exec文件

如何使用数组的最小条目拆分数组

Python键入协议默认值

删除字符串中第一次出现单词后的所有内容

如何请求使用Python将文件下载到带有登录名的门户网站?

实现神经网络代码时的TypeError

如何启动下载并在不击中磁盘的情况下呈现响应?

Tkinter菜单自发添加额外项目

为什么numpy. vectorize调用vectorized函数的次数比vector中的元素要多?

如何在Pyplot表中舍入值

在pandas/python中计数嵌套类别

重置PD帧中的值

为什么调用函数的值和次数不同,递归在代码中是如何工作的?