0

I've created a command where it reads the elements of a text file, and for each element in that text file it creates a button.

for element in myfile:
 button=Button(root, text="hi").pack()

i want to assign to each button a specific value (like if i press one specific button something will appear), but im getting the same command for each button... how can i do that?

1 Answers1

0

I'm not sure what you don't understand in the linked answer. Here are two working examples to experiment with.

import tkinter as tk

root = tk.Tk()

label = tk.Label( root, text = ' Nothing Clicked Yet ')

def button_cmd( obj ):
    label.config( text = obj.cget("text" ) + " clicked." ) 

for ix, caption in enumerate([ 'Button A', 'Button B', 'Button C' ]):
    button = tk.Button( root, text = caption )  # Create the button object
    
    button.config( command = lambda obj = button:  button_cmd( obj ) )
    # Configure the command option. This must be done after the button is 
    # created or button will be the previous button. 
    
    button.pack()

label.pack()

root.mainloop()

An alternative way of creating the closure without using lambda.

root = tk.Tk()

label = tk.Label( root, text = ' Nothing Clicked Yet ')

def make_button_cmd( obj ): 
    # This returns a function bound to the obj
    def func():
        label.config( text = obj.cget("text" ) + " clicked." ) 

    return func

for ix, caption in enumerate([ 'Button A', 'Button B', 'Button C' ]):
    button = tk.Button( root, text = caption )  # Create the button object
    
    button.config( command = make_button_cmd( button ) )
    # Configure the command option. This must be done after the button is 
    # created or button will be the previous button. 
    
    button.pack()

label.pack()

root.mainloop()
Tls Chris
  • 3,564
  • 1
  • 9
  • 24