问题
This is a followup to my question here. I'm trying to use ttk.OptionMenu to enhance the look and feel of a dropdown menu. But as noted in the post here, "A ttk optionmenu widget starts out with all of its values in the dropdown. Upon selecting any value, the first value in the list vanishes, never to reappear..." The workaround as suggested in that post is to add an empty item to the list. In my case, since I am using a dictionary, adding '':[]
as the first item in the dictionary fixed the problem. Is this the only solution? I hate to introduce an artifact into my dictionary. Here's the code:
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
class App:
def __init__(self, master):
master.title("Continental System")
self.dict = {'':[], 'Asia': ['Japan', 'China', 'Malasia'],
'Europe': ['Germany', 'France', 'Switzerland'],
'Africa': ['Nigeria', 'Kenya', 'Ethiopia']}
self.frame1 = ttk.Frame(master)
self.frame1.pack()
self.frame2 = ttk.Frame(master)
self.frame2.pack()
self.variable_a = tk.StringVar()
self.variable_b = tk.StringVar()
self.variable_a.trace('w', self.updateoptions)
self.optionmenu_a = ttk.OptionMenu(self.frame1, self.variable_a, *self.dict.keys())
self.variable_a.set("Asia")
self.optionmenu_a.grid(row = 0, column = 0)
self.optionmenu_b = ttk.OptionMenu(self.frame1, self.variable_b, '')
self.optionmenu_b.grid(row = 0, column = 1)
self.btn = ttk.Button(self.frame2 , text="Submit", width=8, command=self.submit)
self.btn.grid(row=0, column=1, padx=20, pady=20)
def updateoptions(self, *args):
countries = self.dict[self.variable_a.get()]
self.variable_b.set(countries[0])
menu = self.optionmenu_b['menu']
menu.delete(0, 'end')
for country in countries:
menu.add_command(label=country, command=lambda country=country: self.variable_b.set(country))
def submit(self, *args):
var1 = self.variable_a.get()
var2 = self.variable_b.get()
if messagebox.askokcancel("Confirm Selection", "Confirm your selection: " + var1 + ' ' + var2 + ". Do you wish to continue?"):
print(var1, var2)
def set_window(self, *args):
w = 800
h = 500
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
root = tk.Tk()
app = App(root)
app.set_window()
root.mainloop()
Also I am getting some error messages including AttributeError: 'App' object has no attribute 'optionmenu_b'
which seemed to have been resolved in the answer to my first question above.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
return self.func(*args)
File "C:\Python34\tk1_version2.py", line 32, in updateoptions
menu = self.optionmenu_b['menu']
AttributeError: 'App' object has no attribute 'optionmenu_b'
Python Version 3.4.1
回答1:
That post you quote is incorrect. You do not need to put a space as the first item in the list. The signature of the ttk.OptionMenu
command requires a default value as the first argument after the variable name.
You do not need to add an empty item to your dictionary. You do need to add a default value when you create the optionmenu:
self.optionmenu_a = ttk.OptionMenu(self.frame1, self.variable_a, "Asia", *self.dict.keys())
A slightly better solution would be to get the list of keys and save them to a list. Sort the list, and then use the first element of the list as the default:
options = sorted(self.dict.keys())
self.optionmenu_a = ttk.OptionMenu(self.frame1, self.variable_a, options[0], *options)
The reason you get the error is because you have a trace on the variable which calls a function that references self.optionmenu_b
, but you are initially setting that variable before you create self.optionmenu_b
. The simple solution is to create the second menu first.
self.optionmenu_b = ttk.OptionMenu(...)
self.optionmenu_a = ttk.OptionMenu(...)
来源:https://stackoverflow.com/questions/25216135/more-on-tkinter-optionmenu-first-option-vanishes