0

I need to be able to config the button that is clicked inside a function whilst using the function for multiple buttons

Iv'e seen people use the parameters to call the name of the button in the fucntion, however I've already used the parameters for a necessary part of my code so I am unable to do this

clicked = 0
def click_place(position):

    while clicked < 6:
        clicked += 1
        place_positions.append(position)
        .config(bg="yellow") #where I need help


#placement buttons
place_buttons = Frame(window)

place_positions = []

but1 = Button(place_buttons, height = 2, width = 5, command= lambda:click_place('A1'))
but1.grid(row = 0, column = 0)

but2 = Button(place_buttons, height = 2, width = 5, command= lambda:click_place('A2'))
but2.grid(row = 0, column = 2)


place_buttons.place(x=250, y=500, anchor=CENTER) 
  • Why not pass more than one parameter? `click_place(but1, 'A1')` for example, so you have both the button and the string to work with. – jasonharper Oct 25 '19 at 18:38
  • Read [Get the text of a button if clicked](https://stackoverflow.com/a/6205482/7414759) – stovfl Oct 25 '19 at 18:49

1 Answers1

0

The simplest is to store your buttons in a dictionary using 'A1' and 'A2' as keys

buttons = {
    'A1': but1,
    'A2': but2,
}

Then, given that position will be set to 'A1' or 'A2', you can reference the button at position with buttons[position].

Another solution is to pass the button as a parameter:

def click_place(position, button):
    ...
...
but1 = Button(place_buttons, height = 2, width = 5)
but1.configure(command= lambda:click_place('A1', but1))
...
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685