Reputation: 711
So i have simple application
with 2 labels
and 2 option_menu
:
import sys
if sys.version_info[0] >= 3:
import tkinter as tk
else:
import Tkinter as tk
class App(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
def update_options(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 nation=country: self.variable_b.set(nation))
def create_labels(self):
tk.Label(root, text='').grid(row=0)
tk.Label(root, text='Produtct:').grid(row=1, padx=10, pady=5)
tk.Label(root, text='Application:').grid(row=2, padx=10, pady=5)
def create_option_menu(self):
self.dict = {
'Mobile': ['ios', 'android'],
'Test': ['1', '2', '3']
}
self.variable_a = tk.StringVar(self)
self.variable_b = tk.StringVar(self)
self.variable_a.trace('w', self.update_options)
self.optionmenu_a = tk.OptionMenu(self, self.variable_a, *self.dict.keys()).grid(row=1, column=1, sticky="NSWE")
self.optionmenu_b = tk.OptionMenu(self, self.variable_b, '').grid(row=1, column=1, sticky="NSWE")
self.variable_a.set('Mobile')
if __name__ == "__main__":
root = tk.Tk()
app = App(root)
app.create_labels()
app.create_option_menu()
app.mainloop()
And when I select some option from the first option menu
the second option menu
changed accordingly.
And i have problem that I cannot see my option menu
and i cannot figure why.
This is my exception:
Exception in Tkinter callback Traceback (most recent call last):
File "C:\Python37\lib\tkinter_init_.py", line 1705, in call return self.func(*args) File "C:/HW_Automation_Python/robot-framework/gui/init.py", line 19, in update_options menu = self.optionmenu_b['menu'] TypeError: 'NoneType' object is not subscriptable
Upvotes: 0
Views: 196
Reputation: 15098
Just change your respective part of code to this:
self.optionmenu_a = tk.OptionMenu(root, self.variable_a, *self.dict.keys())
self.optionmenu_a.grid(row=1, column=1, sticky="NSWE")
self.optionmenu_b = tk.OptionMenu(root, self.variable_b, '')
self.optionmenu_b.grid(row=2, column=1, sticky="NSWE")
Firstly, you are saying grid()
on the same line as declaration which makes the variable have None
as the value. Check here for more information on this.
Secondly, you forgot to specify a master option, like root
for the widget.
Upvotes: 1