Home > Enterprise >  python tkinter cannot assign stringvar() set
python tkinter cannot assign stringvar() set

Time:02-01

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.

CodePudding user response:

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.

CodePudding user response:

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