In part 3 of my Kivy tutorial series we’ll create a working calculator app in one video. We’ll cover how to use layouts inside of other layouts, event handling, TextInput, executing code based on widget events, and much more.
All of the heavily commented code used follows the video below. Feel free to do whatever you’d like with it.
If you like videos like this consider donating $1 on Patreon.
[googleplusone]
Code & Cheat Sheet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
# ---------- main.py ---------- import kivy kivy.require("1.9.0") from kivy.app import App from kivy.uix.gridlayout import GridLayout class CalcGridLayout(GridLayout): # Function called when equals is pressed def calculate(self, calculation): if calculation: try: # Solve formula and display it in entry # which is pointed at by display self.display.text = str(eval(calculation)) except Exception: self.display.text = "Error" class CalculatorApp(App): def build(self): return CalcGridLayout() calcApp = CalculatorApp() calcApp.run() # ---------- calculator.kv ---------- # Custom button <CustButton@Button>: font_size: 32 # Define id so I can refer to the CalcGridLayout # class functions # Display points to the entry widget <CalcGridLayout>: id: calculator display: entry rows: 5 padding: 10 spacing: 10 # Where input is displayed BoxLayout: TextInput: id: entry font_size: 32 multiline: False # When buttons are pressed update the entry BoxLayout: spacing: 10 CustButton: text: "7" on_press: entry.text += self.text CustButton: text: "8" on_press: entry.text += self.text CustButton: text: "9" on_press: entry.text += self.text CustButton: text: "+" on_press: entry.text += self.text BoxLayout: spacing: 10 CustButton: text: "4" on_press: entry.text += self.text CustButton: text: "5" on_press: entry.text += self.text CustButton: text: "6" on_press: entry.text += self.text CustButton: text: "-" on_press: entry.text += self.text BoxLayout: spacing: 10 CustButton: text: "1" on_press: entry.text += self.text CustButton: text: "2" on_press: entry.text += self.text CustButton: text: "3" on_press: entry.text += self.text CustButton: text: "*" on_press: entry.text += self.text # When equals is pressed pass text in the entry # to the calculate function BoxLayout: spacing: 10 CustButton: text: "AC" on_press: entry.text = "" CustButton: text: "0" on_press: entry.text += self.text CustButton: text: "=" on_press: calculator.calculate(entry.text) CustButton: text: "/" on_press: entry.text += self.text |
Leave a Reply