0
win=Tk()
level1=matrixmaker(4)

def display(x,y): 
if z["text"] == " ":
    # switch to Goodbye
    z["text"] = level1[x][y]
else:
    # reset to Hi
    z["text"] = " "


for x in range(0,4):
    for y in range(0,4):
        z=Button(win,text=" ", command=display(x,y))
        z.grid(row=x,column=y)

I have this code but I don't know how to get the display function to work. How can I call the button and change the text without it having a hardcoded variable name?

5
  • In Tkinter, the command argument is a reference to a function, not the function itself. You have to make the argument into command=display with no arguments. See here: stackoverflow.com/questions/6920302/… Commented Dec 1, 2015 at 23:30
  • Also, you're calling a three argument function with only two arguments (that can't be added anyway). Commented Dec 1, 2015 at 23:32
  • use command=lambda a=x,b=y:display(a,b) Commented Dec 1, 2015 at 23:38
  • i added the lambda but now whenever i click anything on the grid it only changes the bottom right button Commented Dec 1, 2015 at 23:38
  • because you change z - but z is the last button created in for loop. Commented Dec 1, 2015 at 23:39

1 Answer 1

4

You can't assign the command to the button with the called function (display(x, y)) because this assigned what this function returns (None) to the button's command. You need to assign the callable (display) instead.

To do this and pass arguments you'll need to use a lambda:

z = Button(win, text='')
z['command'] = lambda x=x, y=y, z=z: display(x, y, z)
z.grid(row=x, column=y)

Also, you'll want to change your display() function to accept another argument z so that the correct button gets changed (and correct the indentation):

def display(x,y,z): 
    if z["text"] == " ":
        # switch to Goodbye
        z["text"] = level1[x][y]
    else:
        # reset to Hi
        z["text"] = " "
Sign up to request clarification or add additional context in comments.

2 Comments

you should add - OP needs to use def display(x,y,z) in place of def display(x,y)
@furas Thanks for pointing this out (before the OP edited the question it was defined as def display(x,y,z))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.