I know this is an old question, but I think I found a workaround for this limitation of tkinter by internalizing the control variable. Then you don't need to declare a separate value when creating your widgets:
class DynamicLabel(tkinter.Label):
def __init__(self, master, *args, **kwargs):
super().__init__(master=master, *args, **kwargs)
self.master = master
self.value=None
for kwarg, value in kwargs.items():
if kwarg == 'textvariable':
if not isinstance(value, tkinter.StringVar):
raise ValueError('Textvariable must be StringVar')
self.value = value
if not self.value:
self.value = tkinter.StringVar()
self.config(textvariable=self.value)
def set(self, txt):
self.value.set(txt)
def get(self):
return self.value.get()
What this does is creating a proxy for the control variable with self.value
.
Then we will iterate through all kwargs and if textvariable
is found we make self.value
a reference to it.
If no textvariable was set when creating the widget, we just create our own and assign it to the widget with self.config(textvariable=self.value)
All that is left then is to create set and get methods to access the control variable.
I guess the above could be even further simplified by ignoring whichever textvariable
was assigned when creating the widget and always creating a new one from scratch.
You could even make self.value
a property to be able to interact with self.value
directly