-1

I am learning Python's GUI with Tkinter.

I want to create a GUI with many buttons, and every button has own name and similar function(only difference in parameter).

This is my code:

from tkinter import *

ALPHABET = ["1", "2", "3"]

class GUI():
    def __init__(self):
        self.__mainw = Tk()
        self.letter_list = []

        # I want that every button have own name and command function parameter
        for letter in ALPHABET:
            self.letter_list.append(Button(self.__mainw, text=letter, command= lambda : self.letter_btm(letter)))

        for letter_btm in self.letter_list:
            letter_btm.pack()

        self.__mainw.mainloop()

    def letter_btm(self, letter):
        print(letter)

def main():
    GUI()

if __name__ == "__main__":
    main()

and this is result.

enter image description here

Every button print same letter. I know the result maybe variable reference, but how can I get expect result?

Button 1, Print 1

Button 2, Print 2

Button 3, Print 3

1 Answers1

1

I don't know why but this weird syntax seems to work. Has something to do with storing the current value of letter at the time your lambda is defined, instead of waiting to look up the value of letter later.

from tkinter import *

ALPHABET = ["1", "2", "3"]


class GUI:
    def __init__(self):
        self.__mainw = Tk()
        self.letter_list = []

        # I want that every button have own name and command function parameter
        for letter in ALPHABET:
            temp_func = lambda letter=letter: self.letter_btm(letter)
            self.letter_list.append(Button(self.__mainw, text=letter, command=temp_func))

        print(self.letter_list)
        for letter_btm in self.letter_list:
            letter_btm.pack()

        self.__mainw.mainloop()

    def letter_btm(self, letter):
        print(letter)


def main():
    GUI()


if __name__ == "__main__":
    main()
  • 1
    Function parameter with provided default value get assigned the actual value to the parameter evaluated from the expression on the right side of the assignment at the time of function definition. This is the reason why this 'weird syntax' works. – Claudio Oct 09 '22 at 13:11
  • Ohh,Thank you. I'm not familiar with the syntax of lambda。 – BrandonCage Oct 09 '22 at 14:04