Python Tkinter error with button commands

Question:

Hi I was trying to make simple calculator using tkinter gui with python.
But first of all I was trying to create buttons that once they are clicked, they were attached to the result shown on the screen. (Just as real-life calculator, if screen shows 12 and I click 3, the screen then shows 123)

from Tkinter import *
class Calculator(Frame):

    def __init__(self):
        Frame.__init__(self)
        self.master.title('Calculator')
        self.pack()

        self.screen=Frame(self, borderwidth=20, relief=SUNKEN)
        self.screen.pack()
        self.txtDisplay = Text(self.screen, width=20, height=2)
        self.txtDisplay.pack()
        self.screen.grid(row=0, columnspan=5) #columnspan to span multiple columns

        Contents = ['1','2','3','+','4','5','6','-','7','8','9','*','C','0','=','/']
        Buttons = [None]*16
        j=1
        count=0
        for i in range(16):
            Buttons[i]=Button(self, text=Contents[i], command=lambda : self.txtDisplay.insert(END, Contents[i]), height=2, width=5, borderwidth=5)
            Buttons[i].grid(row=j, column=i%4)
            count+=1
            if count%4==0:
                j+=1
                count=0


Calculator().mainloop()

However, the problem is the screen only attaches / whenever I click any button and eventually results in //////////////

enter image description here

/ is last element of Contents list and I guess there is something wrong with

command=lambda : self.txtDisplay.insert(END, Contents[i])

Can I get explanation on why this occurs and how I can deal with it?

Asked By: Jimmy Suh

||

Answers:

Very problem problem with lambda in for loop. You can find many answers.

lambda doesn’t use value from i when you create button but when you press button – so all buttons use the same value i which directs to last button.

You have to assign i to argument in lambda and it will copy value from i when you create button

command=lambda x=i: self.txtDisplay.insert(END, Contents[x])
Answered By: furas
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.