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
  • 4,515
  • 2
  • 17
  • 33
Dante_Annetta
  • 13
  • 1
  • 4

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()
Programmer
  • 5,276
  • 3
  • 9
  • 33
-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()
Programmer
  • 5,276
  • 3
  • 9
  • 33