Search code examples
python-3.xtkinteroptionmenu

Passing OptionMenu into a callback (or retrieving a reference to the used widget)


I'm working on a (toplevel in a) GUI that consists of an array of 8 OptionMenus, each of them containing the same option list. Currently, Im building these widgets using a for-loop, and I save references in a dictionary. All OptionMenus link to the same (lambda) callback function.

To stay practical: the items in the option list represent a sequence of processing steps, and the user can alter the order of processes.

A change in one of the lists will result in one process being executed twice, and one process not at all. However, I want each item to occur only once. Hence, each user input should be accompanied by a second OptionMenu alteration.

For example: initial order 1-2-3 --> user changes the second process: 1-3-3, which autocorrects to: 1-3-2, where each process is again executed only once.

To my understanding, I can only get this to work if I have a reference to the OptionMenu that was just altered (from within the callback function). I was looking into passing the widget into the callback. The sample code is an attempt to implement the second suggested method, but the result is not what I would have expected.

The thing is that the OptionMenu widget seems to behave somewhat differently from other widgets. The OptionMenu does not allow for a re-defintion of the command function. No matter what input I pass along with the command function, the callback only seems to retrieve the OptionMenu selection, which is insufficient information for me to determine my process order.

Suggestions would be much apreciated!

import tkinter as tk

class Application(tk.Frame):

    def __init__(self, master=None):
        super().__init__(master)
        self.grid(row=0, column=0, sticky=tk.N+tk.S+tk.E+tk.W)
        self.create_widgets()


    def create_widgets(self):
        self.active_procs = ['proc 1','proc 2','proc 3','proc 4',
                             'proc 5','proc 6','proc 7','proc 8']
        itemnr, widgets = dict(), dict()
        for index in range(8):
            name_construct = 'nr' + str(index)
            itemnr[name_construct] = tk.StringVar(root)
            itemnr[name_construct].set(self.active_procs[index])
            widgets[name_construct] = tk.OptionMenu(self, itemnr[name_construct], *self.active_procs,
                                                    command=lambda widget=name_construct:
                                                    self.order_change(widget))
            widgets[name_construct].grid(row=index+2, column=2, columnspan=2,
                                         sticky="nwse", padx=10, pady=10)


    def order_change(self,widget):
        print(widget)


root = tk.Tk()
root.title("OptionMenu test")

app = Application(master=root)

root.mainloop()

Solution

  • The OptionMenu will pass the new value to the callback, so you don't have to do anything to get the new value. That's why your widget value isn't the value of name_construct -- the value that is passed in is overwriting the default value that you're supplying in the lambda.

    To remedy this you simply need to add another argument so that you can pass the value of name_construct to the callback to go along with the value which is automatically sent.

    It would look something like this:

    widgets[name_construct] = tk.OptionMenu(..., command=lambda value, widget=name_construct: self.order_change(value, widget))
    ...
    def order_change(self, value, widget):
        print(value, widget)
    

    Note: the OptionMenu isn't actually a tkinter widget. It's just a convenience function that creates a standard Menubutton with an associated Menu. It then creates one item on the menu for each option, and ties it all together with a StringVar.

    You can get the exact same behavior yourself fairly easily. Doing so would make it possible to change what each item in the menu does when selected.