首页 > 解决方案 > 使用列表时,Tkinter 按钮只能工作一次

问题描述

我正在尝试使用按钮循环浏览列表。它工作一次,但不会响应任何其他压力。

cards = ["2 of Diamonds", "3 of Diamonds"] #etc (don't want it to be too long)
current = 0
def next():
   current=+1
   print("\"current\" variable value: ", current)
   card.config(text=cards[current])
next = Button(text="⇛", command=next, fg="White", bg="Red", activebackground="#8b0000", activeforeground="White", relief=GROOVE).grid(column=2, row=1)

有什么建议么?

标签: pythonfunctiontkintertk

解决方案


current1是每次调用函数时初始化的局部变量。

你需要做两件事:

  • 声明current为全局
  • 正确增加它(+=而不是=+

例子:

def next():
    global current
    current += 1
    ...

推荐阅读