Passing StringVar object from Entry to Label within functions in tkinter

后端 未结 2 1803
旧巷少年郎
旧巷少年郎 2021-01-25 21:06

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 var

相关标签:
2条回答
  • 2021-01-25 21:55

    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.

    0 讨论(0)
  • 2021-01-25 22:11

    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:

    class My_Class:
        def start(self): 
            ...
            self.entry_box = Entry(self.root)
            self.button = Button(..., command = self.myFunc)
            ...
    
        def myFunc(self):
            s = self.entry_box.get()
            self.lab = Label(..., text = s)
            ...
    
    0 讨论(0)
提交回复
热议问题