【问题标题】:How do I call self in tkinter button? [duplicate]如何在 tkinter 按钮中调用 self? [复制]
【发布时间】:2023-04-06 03:06:01
【问题描述】:

我正在使用 tkinter 创建一种基于按钮的绘制,所以我想给每个按钮一个命令来绘制自己。

     for i in range(xc*yc):

             grid.append(Button(wn,text="    ",bg="white",padx=5,pady=5))

             grid[-1].config(command = paint(i))  <--????

             grid[-1].place(x= (i%xc) * 30 +60, y = (math.floor(i/xc) * 30)+30)

问题是每个按钮都会收到最终值为 i 的命令“paint(i)”,所以每次它都会绘制最后一个按钮

【问题讨论】:

  • 您的代码不会有上述输出,因为paint(i) 将在分配给command 选项时执行。您提到的输出将在使用 grid[-1].config(command=lambda: paint(i)) 时发生。要解决此问题,请使用grid[-1].config(command=lambda i=i: paint(i))

标签: python button tkinter command self


【解决方案1】:

使用 root.update() 方法强制更新 UI.so 你可以使用它来查看 for 循环的每次迭代,如果你在里面调用它

【讨论】:

  • 但是如何查看迭代?
  • 在 for 循环中使用这个,所以 UI 会更新 for 循环的每次迭代
  • 发送一个工作代码块,然后我会检查错误
【解决方案2】:

可能是这样的

for i in range(xc*yc):
    button = Button(wn,text="    ",bg="white",padx=5,pady=5)
    grid.append(button)
    button.config(command = paint(i, button)) # note the additional reference to button here!
    button.place(x= (i%xc) * 30 +60, y = (math.floor(i/xc) * 30)+30)

会有帮助的。

【讨论】:

  • 遗憾的是它总是调用最后一个按钮:(
猜你喜欢
  • 2021-05-29
  • 2020-12-19
  • 1970-01-01
  • 2019-06-23
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多