Note that my problem is the opposite of this: Creating functions in a loop in that I have many buttons and one function, not many functions.
I create 10 numbered buttons from a for
loop, then try to bind each one to a function that will print the button's number; See code below:
import tkinter as tk
class Window(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
# creating buttons and adding them to dictionary
self.buttons = {}
for number in range(1, 11):
self.buttons.update({'button' + str(number): tk.Button(self, height=1, width=4, bg="grey", text=number)})
# example of a pair in the dictionary: 'button2': <Tkinter.Button instance at 0x101f9ce18>
""" bind all the buttons to callback, each button is
named something like 'button3',so I take the number off
the end of its name and feed that as an argument to Callback"""
for button in self.buttons:
self.buttons[button].bind('<Button-1>', lambda event: self.Callback(event, button[6:]))
self.buttons[button].pack(side='left')
def Callback(self, event, num):
print(num)
All the buttons appear on the window no problem, but when I click any of them, the console prints '10
', as opposed to the button's number. It seems the function is only remembering the last argument it was given.