Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Tkinter button callback

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

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?

like image 352
Chris Aung Avatar asked Aug 30 '26 06:08

Chris Aung


2 Answers

Easy fix is to initialize the lambda function with the current value of i each time the lambda function is created. This can be done using Python default values for another dummy variable j.

command = lambda j=i: myfunction(j)
like image 130
lindyblackburn Avatar answered Aug 31 '26 18:08

lindyblackburn


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()
like image 37
Jared Avatar answered Aug 31 '26 19:08

Jared