Tkinter unexpected behaviour

Tkinter unexpected behaviour

Asked on November 27, 2018 in tkinter.
Add Comment


  • 4 Answer(s)

    Here is the solution is:

        You  keep the  references to i which is mutated as the loop iterates, and in the end all lambdas from the same loop refer to the same single last button.

    Here you can ues the below code

    >>> k = []
    >>> for i in range(5):
    ... k.append(lambda: i)
    >>> k[0]()
    4
    >>> [f() for f in k]
    [4, 4, 4, 4, 4]
    
    Answered on November 27, 2018.
    Add Comment

    Here is the best solution is:

    for i in range(len(buttons)-1):
    buttons[i].bind("<Down>", lambda x, i=i: buttons[i+1].focus_set())
     
    for i in range(1, len(buttons)):
    buttons[i].bind("<Down>", lambda x, i=i: buttons[i-1].focus_set())
    

    Note

    The i=i argument to the lambda closure.

    Answered on November 27, 2018.
    Add Comment

    Your closures (lambdas) are not working as you expect them to. They keep references to i which is mutated as the loop iterates, and in the end all lambdas from the same loop refer to the same single last button.

    Here’s an illustration of the behaviour:

    >>> k = []
    >>> for i in range(5):
    ...     k.append(lambda: i)
    >>> k[0]()
    4
    >>> [f() for f in k]
    [4, 4, 4, 4, 4]
    Answered on February 25, 2019.
    Add Comment

    I have a set of methods in my program the use Tkinter that don’t behave like I thought they would. I want to be able to push a button in the window and have more text fields appear, and be able to return a list of the results in the text fields. Here is what I have:

    def expandChoice(self):
        root = Tk()
    
        choices = []
    
        plusButton = Button (root, text='+', command=self.addChoice(root, choices)) 
        plusButton.pack()
    
        quitButton = Button (root, text='Ok', command=root.destroy ) 
        quitButton.pack()
    
        root.mainloop()
    
        return choices
    
    def addChoice(self, parent, variables):
    
        variables.append(StringVar())
    
        text = Entry(parent, textvariable=variables[len(variables)-1])
        text.pack()
    Answered on April 17, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.