I wanted to create module based tkinter classes. I want to be able var_text
variable to be able to print on Label
text given to it.
from tkinter import *
class Maincl(Tk):
def __init__(self,xwidth,yheight):
super().__init__()
self.geometry(f'{xwidth}x{yheight}')
self.var_text=StringVar()
Labelcl(self,'darkblue',30,3).pack()
Labelcl(self, 'white', 30, 3,self.var_text.set('hello tkinter')).pack()
self.mainloop()
class Labelcl(Label):
def __init__(self,master,bg_color,width,height,text_variable=None):
super().__init__(master)
self.master=master
self.configure(bg=bg_color,width=width,height=height,textvariable=text_variable)
app=Maincl('500','300')
But as of matter, for testing purpose I assigned(set) to var_text
to "hello tkinter" but cannot see text when code is run.
>Solution :
You can set the initial value when creating the StringVar
:
from tkinter import *
class Maincl(Tk):
def __init__(self,xwidth,yheight):
super().__init__()
self.geometry(f'{xwidth}x{yheight}')
# set initial value using `value` option
self.var_text=StringVar(value='hello tkinter')
Labelcl(self,'darkblue',30,3).pack()
# need to pass the variable reference
Labelcl(self, 'white', 30, 3, self.var_text).pack()
self.mainloop()
class Labelcl(Label):
def __init__(self,master,bg_color,width,height,text_variable=None):
super().__init__(master)
self.master=master
self.configure(bg=bg_color,width=width,height=height,textvariable=text_variable)
app=Maincl('500','300')