简体   繁体   中英

Python Tkinter Swapping OptionMenu Selections

For a Python/Tkinter application I'm making, I've got two OptionMenus. I'd like to create a "swap" button that would swap the selections of the two. Both OptionMenus are populated by the same list.

Let's just say for this example the list is of countries, and the first OptionMenu has "Germany" selected, whilst the second OptionMenu has "Netherlands" selected. The function should make the first OptionMenu change it's selection to "Netherlands" and the second to "Germany".

Snippet of relevant code:

unit1 = StringVar()
unit2 = StringVar()
unit1_entry = ttk.Entry(mainframe, width=7, textvariable=unit1)
unit1_entry.grid(column=1, row=1, sticky=(W, E))
unit2_label = ttk.Label(mainframe, textvariable=unit2)
unit2_label.grid(column=1, row=2, sticky=(W, E))
ttk.Button(mainframe, text="Swap" #command needed here#).grid(column=4, row=2, sticky=W)

#FIRST MEASUREMENT
convertFromUnits.set(LENGTH[0])
convertFrom = OptionMenu(mainframe, convertFromUnits, *LENGTH)
convertFrom.grid(column=2, row=1)
convertFrom.config(width=16, justify="center")
#SECOND MEASUREMENT
convertToUnits.set(LENGTH[1])
convertTo = OptionMenu(mainframe, convertToUnits, *LENGTH)
convertTo.grid(column=2, row=2)
convertTo.config(width=16, justify="center")

So yeah I need to create a function that will swap what is set in the two OptionMenus "convertFrom" and "convertTo". Tried a couple things but little working. Any help would be greatly appreciated.

Thanks, Jarrod

I think the best option is to create an auxiliar function to make the swap, a basic example would be

from Tkinter import *

def swap():
    temp=variable1.get()
    variable1.set(variable2.get())
    variable2.set(temp)

master = Tk()

variable1 = StringVar(master)
variable1.set("one") # default value

variable2 = StringVar(master)
variable2.set("one") # default value

w = OptionMenu(master, variable1, "one", "two", "three")
w.pack()

w2 = OptionMenu(master, variable2, "one", "two", "three")
w2.pack()

but = Button(master, text="Swap", command=swap)
but.pack()

mainloop()

Just be careful that your variables are accessible from your function

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