简体   繁体   中英

How to swap values in optionmenu tkinter python?

How can i change values in optionmenu when i press the "change" button?

Here is the code that I wrote so far:

import tkinter as tk

root = tk.Tk()

options =[
"eggs","meat","chicken",
"potato"
]

variable1 = tk.StringVar()
variable1.set(options[0])

om1 = tk.OptionMenu(root,variable1,*options)
om1.pack()


variable2 = tk.StringVar()
variable2.set(options[0])

om2 = tk.OptionMenu(root,variable2,*options)
om2.pack()

button_change = tk.Button(root,text="change")
button_change.pack()


root.mainloop()

please help...

You can swap the values of the two OptionMenu via their associated variables:

def swap_options():
    # save the value of first OptionMenu
    opt1 = variable1.get()
    # set the value of first OptionMenu to that of second OptionMenu
    variable1.set(variable2.get())
    # set the value of second OptionMenu to the saved value of first OptionMenu
    variable2.set(opt1)

button_change = tk.Button(root, text="change", command=swap_options)

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