0

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...

  • What _exactly_ do you want to have happen when you click the button? – Josh Clark Apr 15 '20 at 18:12
  • I want it to change, for example, I have an egg and a potato and then I press the button and I have a potato and an egg and I want it to show up on optionmenu –  Apr 15 '20 at 18:14
  • Does this answer your question? [Updating OptionMenu from List](https://stackoverflow.com/questions/28412496/updating-optionmenu-from-list) – Josh Clark Apr 15 '20 at 18:15
  • I want the values ​​in the optionmenus to be swaped when I press the button. One is the egg and the other is the potato and when I press the button it swaps the place between the optiomenus. –  Apr 15 '20 at 18:23

1 Answers1

0

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)
acw1668
  • 40,144
  • 5
  • 22
  • 34