【问题标题】:Python Tkinter: create multiple buttons using a loopPython Tkinter:使用循环创建多个按钮
【发布时间】:2021-03-23 19:08:45
【问题描述】:

我是 Tkinter 的新手,不知道如何通过将它们组织在一个列表中来创建多个按钮。我能够显示一个按钮,但是当我尝试创建多个时,它不起作用,而是创建一个空白页面。

from tkinter import *
from V2cboard import *
import time


#blueLength=len(blueTokens) # This is the num of blue tokens left on board
#redLength=len(redTokens) # This is the num of red tokens left on board

DispTXT=["Play as Red!","Play as Blue!","Let the Computer play!","Two players!"]
button=[None]

root=Tk()
for i in range(4):
    button[i] = Button(root, text=DispTXT[i], command=boardWindow(i))
    button[i].pack()

root.mainloop()

请理解我是编码和 Tkinter 的新手。

我预计会在窗口中创建 4 个单独的按钮,每个按钮都显示上面列表中的文本。然后,当单击一个时,它会将数字 (i) 发送到我的功能 boardWindow 以执行其他操作。我无法让按钮出现,所以我认为这可能是语法错误或者我误解了 Button 函数的工作原理?我得到了错误

can't invoke "button" command: application has been destroyed

当我尝试创建按钮时?

【问题讨论】:

标签: python tkinter


【解决方案1】:

之所以只出现一个按钮是因为button只有一个值Nonebutton[i] 表示列表button 中的第i 项。因为button 只有一个项目,所以当它尝试更改另一个项目时,您会收到错误(列表分配超出范围)。无需更改索引处的项目,只需将其附加到列表的末尾会更容易。
单击按钮不起作用的原因是由两件事引起的。 command 参数采用函数的名称,因此不要包含 ()。因为您需要i 的值,所以您必须使用称为lambda 的东西。这允许您在命令中使用参数。 command = lambda: boardWindow(i) 可以工作,但它总是使用i 的最后一个值,这不是我们想要的,所以我们使用lambda i=i 来保持对该按钮值的唯一引用。
这是工作代码:

button=[]

root=Tk()
for i in range(4):
    b = Button(root, text=DispTXT[i], command= lambda i = i: boardWindow(i))
    b.pack()
    button.append(b)

root.mainloop()

【讨论】:

  • 非常感谢!这是一个非常有用的解释!
  • 谢谢!我很高兴能帮上忙。
猜你喜欢
  • 1970-01-01
  • 2022-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
  • 2016-01-12
相关资源
最近更新 更多