Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python tkinter cannot assign stringvar() set

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading