Skip to content

Instantly share code, notes, and snippets.

@aliva
Created December 27, 2012 15:01
Show Gist options
  • Save aliva/4388934 to your computer and use it in GitHub Desktop.
Save aliva/4388934 to your computer and use it in GitHub Desktop.
a very simple calculator with kiviy for class
import kivy
kivy.require('1.0.6') # replace with your current kivy version !
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
class MyApp(App):
def build(self):
self.last_result = 0
self.last_action = ''
self.main_box = BoxLayout(orientation='vertical')
self.button_box = BoxLayout(orientation='horizontal')
self.number_box = GridLayout(cols=3)
self.action_box = BoxLayout(orientation='vertical')
self.label = Label(text='0', font_size=20)
self.main_box.add_widget(self.label)
self.main_box.add_widget(self.button_box)
self.button_box.add_widget(self.number_box)
self.button_box.add_widget(self.action_box)
self.numbers = []
for i in (1,2,3,4,5,6,7,8,9,0):
n = Button(text='%d' % i)
n.bind(on_press=self.on_number_button_clicked)
self.numbers.append(n)
self.number_box.add_widget(n)
for i in ('/', '*', '-', '+', '='):
n = Button(text=i)
n.bind(on_press=self.on_action_button_clicked)
self.action_box.add_widget(n)
return self.main_box
def on_number_button_clicked(self, button):
old = self.label.text
if old == '0':
self.label.text = button.text
elif '=' in self.label.text:
self.label.text = button.text
else:
self.label.text += button.text
def on_action_button_clicked(self, button):
if '=' in self.label.text:
self.label.text = self.last_result
if button.text != '=':
self.label.text += button.text
elif button.text == '=':
if len(self.label.text) > 1:
if self.label.text[-1] in ('+', '-'):
self.label.text += '0'
if self.label.text[-1] in ('*', '/'):
self.label.text += '1'
try:
self.last_result = str(eval(self.label.text))
self.label.text += '=' + self.last_result
except ZeroDivisionError:
self.last_result = '0'
self.label.text += '=Error Diversion by zero'
elif len(self.label.text) > 1 and self.label.text[-1] in ('/', '*', '-', '+'):
self.label.text = self.label.text[:-1] + button.text
else:
self.label.text += button.text
if __name__ == '__main__':
MyApp().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment