tkinter OptionMenu subclass command and option issue
I want to create a few OptionMenus with the same configuration and I found this example:
class MyOptionMenu(OptionMenu):
def __init__(self, master, status, *options):
self.var = tk.StringVar(master)
self.var.set(status)
OptionMenu.__init__(self, master, self.var, *options)
self.config(font=('calibri',(10)),bg='white',width=12)
self['menu'].config(font=('calibri',(10)),bg='white')
From my main code I call it like this:
comboBox_value = ['a','b','c']
oM = MyOptionMenu(root,'Select',comboBox_value)
oM.grid(row=5,column=1)
Everything runs, but in the GUI OptionMenu I get one option a,b,c instead of 3 options a then b then c. Also if I try to run it like this:
oM = MyOptionMenu(root,'Select',comboBox_value, command = func1)
oM.grid(row=5,column=1)
I get this error:
om = MyOptionMenu(frame_camera,'Select',comboBox_value, command=update_QE)
TypeError: __init__() got an unexpected keyword argument 'command'
It doesn't know what command is ... Any thoughts on how to remedy these issues?
Solution 1:
You need to pass keyword arguments as well:
class MyOptionMenu(OptionMenu):
def __init__(self, master, status, *options, **kwargs): # added **kwargs
self.var = tk.StringVar(master)
self.var.set(status)
OptionMenu.__init__(self, master, self.var, *options, **kwargs) # passed **kwargs
self.config(font=('calibri',10), bg='white', width=12)
self['menu'].config(font=('calibri',10), bg='white')
...
oM = MyOptionMenu(root, 'Select', *comboBox_value, command=func1)
...
From your posted code, I guess that you have both from tkinter import *
and import tkinter as tk
. Wildcard import is not recommended and so just use the second one.