Feb-20-2018, 04:48 AM
Hey all, I'm trying to create a gui menu to easily run different snippets of code for my programming class in high school. I'm having a problem when using a for loop to shorten the process of setting commands to run parts of a file. Whenever I click on a button with the command set with a for loop it always runs the command for the last button in the cascade, not the one I clicked on.
Here's my menu I'm using to access all the files (Slightly simplified):
As you can see when running the menu code it doesn't matter which button you click on it will always run thing number 3. I have no idea why this is happening as when I type out each command separately it works fine. Thanks for the help!
Here's my menu I'm using to access all the files (Slightly simplified):
from tkinter import * import fl1 def add(file, length): fileMenu = Menu(menuBar) menuBar.add_cascade(label='Stuff', menu=fileMenu) for i in range(1, length+1): fileMenu.add_command(label='Thing '+str(i), command=lambda:file.thing(i)) root = Tk() menuBar = Menu(root) fileMenu = Menu(menuBar) menuBar.add_cascade(label='Files', menu=fileMenu) fileMenu.add_command(label='File 1', command=lambda:add(fl1, 3)) root.config(menu=menuBar) root.mainloop()And here's an example file I'd use to split up the code and make it more manageable:
def thing(num): if num == 1: print('This is thing number 1.') print('\n--------------------\n') elif num == 2: print('This is thing number 2.') print('\n--------------------\n') elif num == 3: print('This is thing number 3.') print('\n--------------------\n') else: print('Thing does not exist.') print('\n--------------------\n')At first I was using different functions for each bit of code, but I couldn't find a way to run each function using the same for loop.
As you can see when running the menu code it doesn't matter which button you click on it will always run thing number 3. I have no idea why this is happening as when I type out each command separately it works fine. Thanks for the help!