简体   繁体   中英

Tkinter OptionMenu Command Possible to Specify Parameters?

Currently new to Tkinter, and while researching I found very little documentation on Tkinter's OptionMenu widget. I'd like to be able to use a single callback function for multiple menus, but I am unable to figure out how to do so.

Currently, my code is something like this:

root = tk.Tk()    
options = ["Option A", "Option B"]
message = "Nothing selected!"

def optionsCallback(selection):
        message.set(selection)
        #more code here
    
optionsMenu = ttk.OptionMenu(root, tk.StringVar(),
                             "Select an option",*options,
                             command = optionsCallback).pack()
optionsLbl = ttk.Label(root, textvariable = message).pack()

Is it possible to specify an additional parameter such that the callback function is able to decipher which OptionMenu is the one calling it?

Something like this:

root = tk.Tk()
message = "Nothing selected!"    
options = ["Option A", "Option B"]
        
def optionsCallback(selection, menu):
    if menu == 'A':
         message.set("this is menu A, " + selection)   
    if menu == 'B':
         message.set("this is menu B, " + selection)

        
optionsMenuA = ttk.OptionMenu(root, tk.StringVar(),
                                 "Select an option",*options,
                                 command = optionsCallback).pack()  #how to specify?

optionsMenuB = ttk.OptionMenu(root, tk.StringVar(),
                                 "Select an option",*options,
                                 command = optionsCallback).pack()  #how to specify?

optionsLbl = ttk.Label(root, textvariable = message).pack()

You can use lambda :

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
message = tk.StringVar(value="Nothing selected!")
options = ["Option A", "Option B"]
        
def optionsCallback(selection, menu):
    if menu == 'A':
         message.set("this is menu A, " + selection)   
    if menu == 'B':
         message.set("this is menu B, " + selection)

        
optionsMenuA = ttk.OptionMenu(root, tk.StringVar(),
                                 "Select an option", *options,
                                 command=lambda x: optionsCallback(x, "A")).pack()

optionsMenuB = ttk.OptionMenu(root, tk.StringVar(),
                                 "Select an option", *options,
                                 command=lambda x: optionsCallback(x, "B")).pack()

optionsLbl = ttk.Label(root, textvariable = message).pack()

root.mainloop()

Note that message has been changed from normal string to StringVar() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM