Reputation: 664
I'm trying to populate a menu based on the data within a set. The only problem is that I want to be able to change a variable later on based on the menu item selected. What I currently have now doesn't work as expected. CurrentGenre is being printed out regardless of whether or not the item in the menu is being selected. Is there something I'm missing? Should I abandoned this line of thinking and try a different method? Should I perhaps be storing each of the self.genreMenu... I make somewhere so that I can refer to them later? Thanks
for g in genres:
self.genreMenu.add_command(label=g)
self.genreMenu.bind("<Button-1>", self.change_genre(g))
print(currentGenre)
def change_genre(self, label):
global currentGenre
currentGenre = label
print (currentGenre)
I changed my code to use the command option in add_command instead. I've tried to use the lamba suggestion as mentioned below but I'm still unsure how to do it. I noticed that when not assigning currentGenre to label, currentGenre gets printed it but when assigned nothing gets printed out except for an initial list of the genres. Here's the code block in it's entirety. genres is a set.
for i in data_load["genres"]:
for j in i:
genres.add(i["name"])
for g in genres:
genre_menus.append(self.genreMenu.add_command(label=g, command=self.change_genre(g)))
#self.genreMenu.bind("<Button-1>", lambda event, g: self.change_genre(event, g))
def change_genre (self, label):
global currentGenre
currentGenre = label
print (currentGenre).
Upvotes: 0
Views: 792
Reputation: 386342
You have to give the menu a reference to a function. This can be done easily with lambda
, which creates an anonymous function. You can have that function call your real function.
for g in genres:
self.genreMenu.add_command(label=g,
command=lambda genre=g: self.change_genre(genre))
For a deeper explanation of lambda, see this answer: Why is Button parameter “command” executed when declared?
Upvotes: 4