在一系列 5 个 Button 对象中,我希望第一个单击的 Button 的“text”参数更新为数字 1。然后,当我单击第二个 Button 时,无论是哪个 Button,我都会喜欢它显示 2,然后显示 3,最多显示 5。
这是我的尝试,它一直显示1并且不迭代。
import tkinter as tk
root = tk.Tk()
root.geometry('300x200')
buttons = []
def callback(num):
buttons[num].config(text=next(iter(range(1, 5))))
for i in range(5):
buttons.append(tk.Button(root, text='?', width=6, height=3, command=lambda x=i: callback(x)))
for j in buttons:
j.pack(side='left')
root.mainloop()
附加信息:我可能很难真正理解回调是如何运行的,使用 lambda 而不是直接调用它,而后者的误用可能是它无法按预期工作的原因。这也是我第一次使用 next() 和 iter(),可能做错了。
最佳答案
您需要将迭代器定义和 next()
调用分开,否则每次都会创建一个新的迭代器。
如果您希望它达到 5,还需要将 6
放入 iter(range(1, 6))
中。
试试这个:
import tkinter as tk
root = tk.Tk()
root.geometry('300x200')
buttons = []
my_iter = iter(range(1, 6))
def callback(num):
buttons[num].config(text=next(my_iter))
for i in range(5):
buttons.append(tk.Button(root, text='?', width=6, height=3, command=lambda x=i: callback(x)))
for j in buttons:
j.pack(side='left')
root.mainloop()
关于python - 单击时,tkinter 在按钮上增量显示整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60073437/