0

I try to access/change button attributes for buttons created in a loop.

My idea was to collect the buttons in a list so that i can access every single button. Is there a better way?

At the moment i try to use the buttons-command to change the text of the clicked button. In the "action"-function i get the error-code "list index out of range" when i try to run the code!?

Since i am a newbie in python and tkinter hours over hours passed so far to find a solution without success. Every idea would be very appreciated.

I used quite the same code without creating a list. The code was working but when i clicked a button only the last created button changed the text. Could it be that somehow i have to use the "StringVar"-function or "textvariable"?

import tkinter as tk


window = tk.Tk()
window.geometry("300x150")
window.title("Tic Tac Toe")


def action(i):
    btns[i].configure(text = 'X')


btn_nr = -1
btns = []
for x in range(1,4):
    for y in range(1,4):
        btn_nr += 1
        print(btn_nr)
        btns.append(tk.Button(text='-', command = action(int(btn_nr))))
        btns[int(btn_nr)].grid(row=x, column=y)

exit_button = tk.Button(text='Exit Game', command=window.destroy)
exit_button.grid(row=4, column=1, columnspan=15)


window.mainloop()
Florian_
  • 51
  • 2
  • 7
  • Have you done any research? There are lots of questions and answers on this site related to creating buttons in a loop. – Bryan Oakley Oct 23 '19 at 17:59
  • @BryanOakley: I mostly searched using google and spend a lot of hours for real. But now i was successful by searching directly in stackoverflow. Thanks for the note ;-) Found the solution [here](https://stackoverflow.com/questions/44588154/python-tkinter-how-to-config-a-button-that-was-generated-in-a-loop) Finally soooo happy to continue with coding :-) – Florian_ Oct 23 '19 at 19:12

1 Answers1

1

You were almost there. See below matter being resolved as you need a lambda to pass the btn_nr to the function action. By the way there is no need for int()

import tkinter as tk

window = tk.Tk()
window.geometry("300x150")
window.title("Tic Tac Toe")


def action(button):

    if btns[button].cget('text') == '-':
        btns[button].configure(text='X')

    else:
        btns[button].configure(text='-')


btn_nr = -1
btns = []

for x in range(1, 4):

    for y in range(1, 4):

        btn_nr += 1
        print(btn_nr)

        btns.append(tk.Button(text='-', command=lambda x=btn_nr: action(x)))
        btns[btn_nr].grid(row=x, column=y)

exit_button = tk.Button(text='Exit Game', command=window.destroy)
exit_button.grid(row=4, column=1, columnspan=15)

window.mainloop()

I changed the action function a little to make it toggle between 'X' and '-'.

Bruno Vermeulen
  • 2,970
  • 2
  • 15
  • 29