user2455869
user2455869

Reputation: 151

Tkinter OptionMenu empty dictionary

I have an OptionMenu widget that is usually filled with a list (like a course list).

    self.var_course = StringVar(self.add_window)
    if len(courses) > 0:
        self.var_course.set(self.courses.keys()[0])
    course_drop = OptionMenu(self.add_window, self.var_course, *self.courses).\
        grid(row=0, column=1)
    Button(self.add_window, text="New", height=1, width=1).\
        grid(row=0, column=2)  

Sometimes, this list will be empty because the user has not added any classes. This is causing an error in the creation of course_drop.

File "blah/blah/blahblablah", line 32, in blah
course_drop = OptionMenu(self.add_window, self.var_course, *self.courses).
\TypeError: __init__() takes at least 4 arguments (3 given)

When the dictionary has values, the code works fine, however when it is empty I get the above error. I assume the empty dictionary (self.courses) is not seen as a variable and thus not enough are passed. How can I get around this?

Upvotes: 0

Views: 2001

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49318

try:
    course_drop = OptionMenu(self.add_window, self.var_course,
                  *self.courses).grid(row=0, column=1)
except TypeError:
    pass # display an error, prompt for something that will allow a retry, whatever

Another option:

    course_drop = OptionMenu(self.add_window, self.var_course,
                  *self.courses if self.courses else 0).grid(row=0, column=1)
                  # pick a default value that makes sense if 0 does not

Finally, keep in mind that mywidget = Widget(option=value).grid() assigns the return value of grid() to mywidget, which is None. You should grid() your widgets in a separate statement following their assignment.

Upvotes: 1

Related Questions