1

I am fairly new to working with tkinter in python and ran into trouble getting the name of some buttons created from a loop. In theory, pressing a button should print the name of the button pressed.

This is my code:

import tkinter as tk

def f ():
    print ("Frame:", frm.winfo_children())

root = tk.Tk()
frm = tk.Frame(root)

for i in range (0,3):
  bt = tk.Button(frm,text = str(i),name = str(i),command = f).pack()
frm.pack()

root.mainloop()
J. M. Arnold
  • 6,261
  • 3
  • 20
  • 38
Dante_Annetta
  • 13
  • 1
  • 5

2 Answers2

0

You can pass the number to the callback function with lambda:

import tkinter as tk

def f(name):
    print ("Frame:", frm.winfo_children())
    print(name)

root = tk.Tk()
frm = tk.Frame(root)

for i in range (0, 3):
    bt = tk.Button(frm, text = str(i), name = str(i), command = lambda i=i: f(str(i)))
    bt.pack()

frm.pack()

root.mainloop()
TheEagle
  • 5,808
  • 3
  • 11
  • 39
  • Yes, but with this the f function only returns the last value of i it has, since the buttons will be used once the for loop has finished. I am waiting that when I press a button I print the name of it – Dante_Annetta Jan 21 '21 at 14:49
  • @Dante_Annetta @frederic You need to write `lambda i=i: f(str(i))` as described [here](https://stackoverflow.com/a/49617454/6486738). – Ted Klein Bergman Jan 21 '21 at 14:51
  • @Dante_Annetta i tested my code and it works now. – TheEagle Jan 21 '21 at 14:54
  • @Dante_Annetta please accept my answer by clicking the grey checkmark on the left of it – TheEagle Jan 21 '21 at 15:01
-3

This should work

import tkinter as tk

def f (): 
    print ("Frame:", frm.winfo_children())

root = tk.Tk() 
frm = tk.Frame(root)

for i in range (0, 3): 
    bt = tk.Button(self, frm, text = str(i), name = str(i), command = f)
    bt.pack() 
frm.pack()

root.mainloop()
TheEagle
  • 5,808
  • 3
  • 11
  • 39