Search code examples
pythontkinterlambdaoptionmenu

Tkinter Passing StringVar.get through command lambda gives initial value


Okay, so I am trying to make a menu system using Tkinter and am trying to save the string value of the drop down menu to a class variable. I have code to handle that part, but the problem comes with getting that string value to the function I have written. I know that it isn't my function that is the problem as I am using the print function for my example below.

import tkinter as tk
from enum import Enum

class CustomEnum(Enum):
    Option1 = 'Option1'
    Option2 = 'Option2'


class window():
    def __init__(self, root):
        self.value = CustomEnum.Option1

        test = tk.StringVar()
        test.set(self.value.value)

        tk.OptionMenu(root, test, *[e.value for e in CustomEnum], command = lambda
            content = test.get() : print(content)).pack()

        tk.Button(root, text="Save",
            command =  lambda content = test.get() : print(content)).pack()


root = tk.Tk()
test = window(root)
root.mainloop()

If you run this code, it'll constantly print "Option 1" despite what option you chose or if you add or remove elements (aside from removing Option 1).


Solution

  • The problem lies in this line

    tk.Button(root, text="Save",
        command = lambda content = test.get() : print(content)).pack()
    

    You are assigning content the value of test.get() which was at that instant (Option1) and it continues to be so unchanged.

    Since you want the current value of test.get(), you would have to do this

    command = lambda: print(test.get())).pack()
    

    Also, I believe you have misspelt customEnum instead of CustomEnum.