Skip to content Skip to sidebar Skip to footer

Passing Stringvar Object From Entry To Label Within Functions In Tkinter

Hi I've been struggling to get this to work, each time i change something I receive another error. I've been trying to create an entry box with a function and then get the variable

Solution 1:

This is the correct way to create a StringVar object:

text = StringVar() # note additional ()

Can you explain me what x is in the following statement:

lambda: x.myFunc(self.my_variable.get(self))

x is not visible inside the class, because it's declared outside the class.

myFunc is not indented correctly: you should indent it like the __init__ method.

I really recommend you to watch some tutorials on OOP before proceeding. You are basically trying to guess how OOP works.

Solution 2:

If you make myFunc A method if the class (which you might be trying to do; it's hard to know because your indentation is wrong), you don't have to pass anything to myFunc. That function has access to everything in the class, so it can get what it needs, when it needs it. That lets you eliminate the use of lambda, which helps reduce complexity.

Also, you normally don't need a StringVar at all, it's just one more thing to keep track of. However, if you really need the label and entry to show exactly the same data, have them share the same textvariable and the text is updated automatically without you having to call a function, or get the value from the widget, or set the value n the label.

Here's an example without using StringVar:

classMy_Class:defstart(self): 
        ...
        self.entry_box = Entry(self.root)
        self.button = Button(..., command = self.myFunc)
        ...

    defmyFunc(self):
        s = self.entry_box.get()
        self.lab = Label(..., text = s)
        ...

Post a Comment for "Passing Stringvar Object From Entry To Label Within Functions In Tkinter"