This article mainly describes the Python implementation of the calculator function, involving Python arithmetic, inverse, percentage and other related mathematical operation implementation skills, the need for friends can refer to the following
The examples in this article describe the calculator functionality that Python implements. Share to everyone for your reference, as follows:
Source:
#-*-Coding:utf-8-*-#! Python2from tkinter Import *__author__ = ' tianshl ' __date__ = ' 2017/10/16 ' class application (Frame): def __init__ (self): Fr Ame.__init__ (self) self.grid () Self.mem = "# data in memory self.opt = ' # operator Self.display = Stringvar () # Display of data SE Lf.display.set (' 0 ') # initial value self.need_cls = False # Whether to clear the screen self.create_widgets () # Clear def Clear (self): Self.mem = ' s Elf.display.set (' 0 ') # take anti-def negative (self): Self.display.set (eval ('-' + Self.display.get ())) # Arithmetic def option (Self, op T): If not self.need_cls:self.calculate () self.opt = opt Self.need_cls = True Self.mem = self.display.get () # calculation result def calculate (self): if Self.opt:try:self.display.set (eval (self.mem + self.opt + self.display.get ())) except EXC Eption:self.display.set (' error ') Self.need_cls = True self.opt = ' Self.mem = ' # percent def percent (self): base = Float (self.mem or 1)/display = eval (' {}*{} '. Format (Self.display.get (), base)) Int_display = Int (display) Display = Int_display if display = = Int_display Else display self.display.set (display) self.need_cls = True # Enter DEF input (sel F, key): If Self.need_cls:self.display.set (' 0 ') Self.need_cls = False display = Self.display.get () if display = = ' 0 ' and key! = '. ': Self.display.set (key) Else:if '. ' in display and key = = '. ': Return Self.display.set (display + key) # Create component Def create_widgets (self): # Show Box Entry (Self, textvariable=self.display, state= "ReadOnly", width=35). Grid ( Row=0, Column=0, columnspan=4) # keyboard keyboards = [[' C ', ' +/-', '% ', '/'], [' 7 ', ' 8 ', ' 9 ', ' * '], [' 4 ', ' 5 ', ' 6 ' , '-'], [' 1 ', ' 2 ', ' 3 ', ' + '], [' 0 ', '. ', ' = ']] for row, keys in Enumerate (keyboards): Row_num = 3 + row for Col , key in Enumerate (keys): if key = = ' C ': command = self.clear elif key = = ' + + ': Command = self.negative elif key = = '% ': Command = self.percent elif key in [' + ', '-', ' * ', '/']: Command = lambda s=key:self.option (s ) elif key = = ' = ': Command = self.calculate Else:command = lambda S=key:self.input (s) bt = Button (self, text=key, Command=comma nd, width=6) bt.grid (Row=row_num, column=col) app = Application () # set window title: App.master.title (' www.jb51.net-calculator ') # set window size /Location App.master.geometry ("326x170+200+200") # Set Window immutable app.master.resizable (Width=false, Height=false) # main message loop: App.mainloop ()
Operating effect: