简体   繁体   English

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

[英]tkinter incrementally display integers on buttons when clicked

In a series of say 5 Button objects, I would like that the first clicked Button sees its 'text' parameter updated to the number 1. Then, when I click a second Button, no matter which one, I would like it to display 2, then 3, up to 5.在一系列 5 Button 对象中,我希望第一个单击的 Button 看到其“文本”参数更新为数字 1。然后,当我单击第二个 Button 时,无论是哪个,我都希望它显示 2 ,然后是 3,直到 5。

Here is my attempt, it keeps displaying 1 and does not iterate.这是我的尝试,它一直显示 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()

additional information: I might have difficulties to really understand how callback operates, using lambda instead of calling it directly, and a misuse of the latter might be the reason it is not working as expected.附加信息:我可能很难真正理解回调是如何操作的,使用 lambda 而不是直接调用它,并且滥用后者可能是它没有按预期工作的原因。 It is also the first time I am using next() and iter(), and might have done it wrong.这也是我第一次使用 next() 和 iter(),可能是我做错了。

You need to separate your iterator definition and the next() calls, otherwise you were creating a new iterator each time.您需要将迭代器定义和next()调用分开,否则每次都会创建一个新的迭代器。

You also need to put 6 in iter(range(1, 6)) if you want it to go up to 5.如果您希望它增加到 5 iter(range(1, 6))您还需要将6放入iter(range(1, 6))

Try this :尝试这个 :

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()

Consider the below:考虑以下问题:

buttons[num].config(text=next(iter(range(1, 5))))

You are creating a new iterator every time you click the button.每次单击按钮时,您都在创建一个新的迭代器。 Instead, you should define it in global scope, and call next on it during each button click:相反,您应该在全局范围内定义它,并在每次单击按钮时调用 next :

a = iter(range(1, 5))

def callback(num):
    buttons[num].config(text=next(a))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM