python - 单击时,tkinter 在按钮上增量显示整数

标签 python tkinter callback

在一系列 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/

相关文章:

python - clang.cindex.Libclang错误 "Undefined symbol clang_CXXRecord_isAbstract"

python - wxpython 将变量传递给回调事件。 lambda 岛

python - tkinter py2app 应用程序不会关闭

python - Tkinter tkFileDialog 不存在

javascript - 从回调调用方法时如何从方法获取正确的类上下文

python - sklearn : scaling x (data) and y (target) using both Pipeline and TransformedTargetRegressor

python - 在自己的 Ubuntu 服务器上部署 Flask 应用程序错误

python - 使用用户 tkinter 输入作为 Matplotlib 的坐标绘制一条线

ios - 从 ListView 中保存数据的正确方法是什么?

javascript - 如何在 Javascript 中向 .submit() 添加回调函数?