0

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.

2 Answers 2

2

set() on any tkinter variable will not return anything. So, text_variable is always None as self.var_text.set('hello tkinter') will return None.

self.var_text.set('hello tkinter')
Labelcl(self, 'white', 30, 3,self.var_text).pack()

Here, it will pass the StringVar instance itself.

Sign up to request clarification or add additional context in comments.

2 Comments

but you did not assign StringVar(). It does not show on my pC
@xlmaster In your code, you have specified self.var_text as StringVar.
1

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')

3 Comments

I have accepted your answer. Because when you run the script it shows. But when I import module and run, window and labels are shown but not the text. What can be reason?
@xlmaster If you import this from other script, there may be more than one instance of Tk() which may be the cause of your issue.
@xlmaster add master=self inside the StringVar(...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.