Python: Tkinter Menu entries do not pass correct value Python: Tkinter Menu entries do not pass correct value tkinter tkinter

Python: Tkinter Menu entries do not pass correct value


Change the command to:

lambda the_year=the_year: year_seter(the_year)

The problem has to do with how Python looks up the value of the_year.When you use

lambda : year_seter(the_year)

the_year is not in the local scope of the lambda function, so Python goes looking for it in the extended, global, then builtin scopes. It finds it in the global scope. The for-loop uses the_year, and after the for-loop ends, the_year retains its last value, 2011. Since the lambda function is executed after the for-loop has ended, the value Python assigns to the_year is 2011.

In contrast, if you use a parameter with a default value, the default value is fixed at the time the function (lambda) is defined. Thus, each lambda gets a different value for the_year fixed as the default value.

Now when the lambda is called, again Python goes looking for the value of the_year, but this time finds it in the lambda's local scope. It binds the default value to the_year.


PS.

  1. You could also forgo defining year_seter and just do:

    lambda the_year=the_year: year.set(the_year)
  2. list_of_years = range(1995,2012) also works.