Python Tkinter 按钮回调 [英] Python Tkinter button callback
问题描述
当我单击由 for 循环创建的每个按钮时,我试图打印出按钮编号.以下是我尝试过的.
I am trying to print out the button number when i click each buttons that are created by for loop. The following is what i have tried.
import Tkinter as tk
root=tk.Tk()
def myfunction(a):
print a
for i in range(10):
tk.Button(root,text='button'+str(i),command=lambda:myfunction(i)).place(x=10,y=(10+(25*i)))
root.mainloop()
但它不是打印出每个按钮编号,而是每次都给我最后一个按钮编号.有什么我可以做的,以便当我单击按钮 1 时,它会为 2 打印 1,2,依此类推?
But instead of printing out each button number, it actually giving me the last button number everytime. Is there anything i can do so that when i click button 1, it will print 1,2 for 2 ,and so on?
推荐答案
Blender 的答案是一个聪明的解决方案,但如果您被函数抽象所困扰,这里是另一种可能的方法.它实际上只是创建了一个映射,保存在 buttons
中,从 Button
小部件到其正确的数字.
Blender's answer is a clever solution but in case you get thrown off by the function abstraction, here is another possible way to do it. It really just creates a mapping, saved in buttons
, from Button
widgets to their proper numbers.
import Tkinter as tk
root = tk.Tk()
def myfunction(event):
print buttons[event.widget]
buttons = {}
for i in range(10):
b = tk.Button(root, text='button' + str(i))
buttons[b] = i # save button, index as key-value pair
b.bind("<Button-1>", myfunction)
b.place(x=10,y=(10+(25*i)))
root.mainloop()
这篇关于Python Tkinter 按钮回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!