Jump to content

[Python] Need help with simple graphical calculator program

Go to solution Solved by Mr_KoKa,

In your example lambda is used for create small function really fast, so your:

bttn_0["command"] = lambda: op1.num_press(0);

is like:

def functionForButton0():	op1.num_press(0);bttn_0["command"] = functionForButton0;

and then it can be called by:

bttn_0["command"]();

so it will just run op1.num_press(0);.

If you wouldn't use lambda and do this:

bttn_0["command"] = op1.num_press(0);

"command" key would containt result of function call op1.num_press(0), not a new function.


For a quick example try run this:

class Test():	def fun(self, s):		print "Hello %s!" % (s)		testObj = Test();testObj.fun("world");buttonDict = {'command': None}buttonDict['command'] = lambda: testObj.fun("IcedEskimo");buttonDict['command']();
 # calculator.py - a Python calculatorfrom Tkinter import *class Calc():    def __init__(self):        self.total = 0        self.current = ""        self.new_num = True        self.op_pending = False        self.op = ""        self.eq = False      def num_press(self, num):        self.eq = False        temp = text_box.get()        temp2 = str(num)              if self.new_num:            self.current = temp2            self.new_num = False        else:            if temp2 == '.':                if temp2 in temp:                    return            self.current = temp + temp2        self.display(self.current)     def calc_total(self):        self.eq = True        self.current = float(self.current)        if self.op_pending == True:            self.do_op()        else:            self.total = float(text_box.get())     def display(self, value):        text_box.delete(0, END)        text_box.insert(0, value)     def do_op(self):        if self.op == "add":            self.total += self.current        if self.op == "minus":            self.total -= self.current        if self.op == "times":            self.total *= self.current        if self.op == "divide":            self.total /= self.current        self.new_num = True        self.op_pending = False        self.display(self.total)     def operation(self, op):         self.current = float(self.current)        if self.op_pending:            self.do_op()        elif not self.eq:            self.total = self.current        self.new_num = True        self.op_pending = True        self.op = op        self.eq = False     def cancel(self):        self.eq = False        self.current = "0"        self.display(0)        self.new_num = True     def all_cancel(self):        self.cancel()        self.total = 0     def sign(self):        self.eq = False        self.current = -(float(text_box.get()))        self.display(self.current) op1 = Calc()root = Tk()calc = Frame(root)calc.grid() root.title("Calculator")text_box = Entry(calc, justify=RIGHT)text_box.grid(row = 0, column = 0, columnspan = 4, pady = 5)text_box.insert(0, "0") numbers = "789456123"i = 0bttn = []for j in range(1,4):    for k in range(3):        bttn.append(Button(calc, text = numbers[i],width = 5, height = 2))        bttn[i].grid(row = j, column = k, pady = 5)        bttn[i]["command"] = lambda x = numbers[i]: op1.num_press(x)        i += 1 bttn_0 = Button(calc, text = "0",width = 5, height = 2)bttn_0["command"] = lambda: op1.num_press(0)bttn_0.grid(row = 4, column = 1, pady = 5) bttn_div = Button(calc, text = chr(247),width = 5, height = 2)bttn_div["command"] = lambda: op1.operation("divide")bttn_div.grid(row = 1, column = 3, pady = 5) bttn_mult = Button(calc, text = "x",width = 5, height = 2)bttn_mult["command"] = lambda: op1.operation("times")bttn_mult.grid(row = 2, column = 3, pady = 5) minus = Button(calc, text = "-",width = 5, height = 2)minus["command"] = lambda: op1.operation("minus")minus.grid(row = 3, column = 3, pady = 5) point = Button(calc, text = ".",width = 5, height = 2)point["command"] = lambda: op1.num_press(".")point.grid(row = 4, column = 0, pady = 5) add = Button(calc, text = "+",width = 5, height = 2)add["command"] = lambda: op1.operation("add")add.grid(row = 4, column = 3, pady = 5) neg= Button(calc, text = "+/-",width = 5, height = 2)neg["command"] = op1.signneg.grid(row = 5, column = 0, pady = 5) clear = Button(calc, text = "C",width = 5, height = 2)clear["command"] = op1.cancelclear.grid(row = 5, column = 1, pady = 5) all_clear = Button(calc, text = "AC",width = 5, height = 2)all_clear["command"] = op1.all_cancelall_clear.grid(row = 5, column = 2, pady = 5) equals = Button(calc, text = "=",width = 5, height = 2)equals["command"] = op1.calc_totalequals.grid(row = 5, column = 3, pady = 5) root.mainloop()
 
I need help with the lambda function in, for example, here.
 bttn_0 = Button(calc, text = "0",width = 5, height = 2)bttn_0["command"] = lambda: op1.num_press(0)bttn_0.grid(row = 4, column = 1, pady = 5)
 
Usually, when you use the lambda function, its something like this:
x=lambda n,p:n+pprint x(5,6)

so how does it work there?

Link to post
Share on other sites

In your example lambda is used for create small function really fast, so your:

bttn_0["command"] = lambda: op1.num_press(0);

is like:

def functionForButton0():	op1.num_press(0);bttn_0["command"] = functionForButton0;

and then it can be called by:

bttn_0["command"]();

so it will just run op1.num_press(0);.

If you wouldn't use lambda and do this:

bttn_0["command"] = op1.num_press(0);

"command" key would containt result of function call op1.num_press(0), not a new function.


For a quick example try run this:

class Test():	def fun(self, s):		print "Hello %s!" % (s)		testObj = Test();testObj.fun("world");buttonDict = {'command': None}buttonDict['command'] = lambda: testObj.fun("IcedEskimo");buttonDict['command']();
Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×