0

I am an experienced Python programmer but currently need to implement a basic GUI through Tkinter. It is clear that Python is not rearing at the bit to become the best UI/UX platform, which I complete get, but I am stuck with a basic problem that I cannot seem to find an easy resolution to on the web.

I need to implement a Recent Files list of variable length. So I try to do this:

def __file_menu(self):
        menu = tk.Menu(self, tearoff=False)
        menu.add_command(label="New Project...", command=self.__file_new, state=tk.DISABLED)
        menu.add_command(label="Open Project...", command=self.__file_open)
        recent_list = tk.Menu(menu, tearoff=False)
        for index, project in enumerate(self._recent_projects):
            name = os.path.basename(project).title()
            recent_list.add_command(label=name, command=lambda: self.__open_recent(index))
        menu.add_cascade(label="Recent Projects...", menu=recent_list)

This works a charm for displaying the correct items but what I cannot get right is to pass a unique value in the lambda function that identifies which of the menu items have been selected so I can use it over here:

    def __open_recent(self, item):
        self.__load_project(self._recent_projects[item])

The value of index is always the same namely its last value. So, how do I get a unique identifier (a name, an index etc) from the menu item selected?

Paul
  • 813
  • 11
  • 27

1 Answers1

1

You have to change the lambda to something like this:

recent_list.add_command(label=name, command=lambda i = index: self.__open_recent(i))

This passes the correct index to the function.

Henry
  • 3,472
  • 2
  • 12
  • 36
  • Yeah, of course. I was focusing so much on Tkinter that I completely missed that my lambda was all screwed up!. Thanks. – Paul Jan 26 '21 at 12:41
  • Glad I could help. Please accept this answer if it solved your problem. – Henry Jan 26 '21 at 12:44