0

I am making a GUI Hangman and I have made 26 buttons for each letter. I want to disable the button when pressed but I can't seem to call the variable from the function.

Here is an example button:

self.letter_n = tk.Button(self, text="n", command=lambda: self.take_guess("n"), width=2, height=2).place(x=450, y=400, anchor="center") # Letter "n" (Button)

I have tried to do this but button returns None for some reason.

def take_guess(self, letter):
    button = getattr(self, f"letter_{letter}")
    button.configure(state="disabled")

I have also tried to make a dictionary for each letter and variable like this:

self.dict_of_letters = {"a": self.letter_a,
                    "b": self.letter_b} # And so on...

And using it in the function like this but it still returns None

def take_guess(self, letter):
    button = self.dict_of_letters[letter]

Can anybody help me? This is really annoying and i'm not sure how to do this... I'm happy to provide more info.

1 Answers1

3

In function chaining, the return value of the rightmost function in the chain is assigned to the variable. For example, in

var = foo().bar().baz()

var is assigned whatever is returned from baz(). In your example, you not only create a button instance with tk.Button(), you then call its place() function. tk.Button() returns a button object, but place() simply returns None.

The solution is to create all the button instances, store them in a list or dict, then iterate over all of them to place() them.

MattDMo
  • 100,794
  • 21
  • 241
  • 231