Python - How to 'set' an argument? Python - How to 'set' an argument? tkinter tkinter

Python - How to 'set' an argument?


Change your Text function to be a closure:

def Text(I):    def inner():        print(I)    return inner

Then change your add function to be this:

def add():    global I    text = Text(I)    menu1.add_command(label=I, command=text)    I=I+1

This will save the I in the text variable. The text variable is actually a function, inner, that will print I when called.

Or you could make your closure inline if you wanted to use the Text function somewhere else:

import functools...    menu1.add_command(label=I, command=functools.partial(Text, i))


I think your problem is the lambda:Text(I). In this case, you have created a closure, but the closure knows I to be a global and is evaluating it at a later date.

You probably want to immediately evaluate Text(I) and use that as your result:

texti = Text(I)   # Immediate evaluationmenu1.add_command(label=I, command=lambda:texti)  # Return prior value of "I"