0

So i am genertaing a grid of 3x3 buttons for a Tic Tac Toe game im making, and i want to to end up so that when a button is pressed it changes to either a X or O, however i dont know how to give each button a unique identifier so i know which button to change.

Heres the code for the buttons.

num=1
for row in range(3):
for column in range(3):
    Button(TTTGrid,bg="#ffffff",  width=20,height = 6, command=lambda row=row, column=column: TTTGridPress(row, column),relief=SUNKEN).grid(row=row, column=column, sticky=W)
    num=num+1
mexO
  • 39
  • 2

2 Answers2

1

Use a dictionary or list. For example:

buttons = {}
for row in range(3):
    for column in range(3):
        buttons[(row, column)] = Button(...)
        buttons[(row, column)].grid(...)

Later, you can refer to the button in row 2, column one as:

buttons[(2 1)].configure(...)

Note: you need to call grid (or pack, or place) in a separate statement, because they return None. If you do it on the same statement (eg: Button(...).grid(...)), the value that gets saved is None rather than the instance of the button.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Alright im quite new to this GUI stuff so i got some questions. – mexO Oct 13 '16 at 21:27
  • No 1 - When i do this (buttons[(2 1)].configure(...)), can i replace 2,1 with row, column? So that any button can be clicked in any order. Also i dont really understand the last paragraph, can you explain it a little more please? – mexO Oct 13 '16 at 21:28
  • before asking questions, try it and see. – Bryan Oakley Oct 13 '16 at 21:36
  • I have and it works, but can you still explain the second paragraph further please. – mexO Oct 13 '16 at 21:49
  • @mexO: I don't know how to explain it any clearer. Maybe this will help: http://stackoverflow.com/a/1101765/7432 – Bryan Oakley Oct 13 '16 at 21:51
0

Actually, I also had this kind of tkinter identifier issue. So I got an answer to it. If every row has a unique row and column combination number. So you can create an identifier using that combination and then you call the lambda function. Here I call the arguments using formatted way. It helps to create a unique identifier here.

 TTTGridPress(f'{row}-{column}')

I supposed you can solve your problem now.

num=1
for row in range(3):
for column in range(3):
    Button(TTTGrid,bg="#ffffff",  width=20,height = 6, command=lambda row=row, column=column: TTTGridPress(f'{row}-{column}'),relief=SUNKEN).grid(row=row, column=column, sticky=W)
    num=num+1