Python Gui Calculator Without Tkinter
Creating a Python GUI calculator without using Tkinter requires choosing an alternative framework that offers more modern features and better performance. This guide explores three popular alternatives: PyQt, Kivy, and PySimpleGUI, providing code examples and comparisons to help you build professional desktop applications.
Introduction
Tkinter is Python's standard GUI library, but it has several limitations including an outdated look, limited widgets, and difficulty in creating complex UIs. For more professional applications, developers often turn to alternative frameworks that offer better performance, modern design capabilities, and cross-platform support.
This guide assumes you have basic Python knowledge and have installed Python 3.6 or later on your system.
Alternatives to Tkinter
When building a Python GUI calculator without Tkinter, you have several excellent options:
1. PyQt
PyQt is a set of Python bindings for the Qt framework, which is widely used in professional applications. It provides a rich set of widgets, excellent performance, and the ability to create complex UIs.
2. Kivy
Kivy is an open-source Python library for developing multitouch applications. It's particularly well-suited for mobile development but can also create desktop applications with a modern, touch-friendly interface.
3. PySimpleGUI
PySimpleGUI is a wrapper around several popular GUI frameworks including Tkinter, Qt, WxPython, and Remi. It provides a simple API for creating desktop applications with minimal code.
PyQt Example
Here's a simple calculator implementation using PyQt:
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLineEdit, QPushButton, QGridLayout
class Calculator(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("PyQt Calculator")
self.setFixedSize(300, 400)
central_widget = QWidget()
self.setCentralWidget(central_widget)
layout = QVBoxLayout()
central_widget.setLayout(layout)
self.display = QLineEdit()
self.display.setReadOnly(True)
self.display.setFixedHeight(50)
layout.addWidget(self.display)
grid = QGridLayout()
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+'
]
row, col = 0, 0
for text in buttons:
button = QPushButton(text)
button.clicked.connect(self.on_button_click)
grid.addWidget(button, row, col)
col += 1
if col > 3:
col = 0
row += 1
layout.addLayout(grid)
def on_button_click(self):
button = self.sender()
current_text = self.display.text()
if button.text() == '=':
try:
result = str(eval(current_text))
self.display.setText(result)
except:
self.display.setText("Error")
else:
self.display.setText(current_text + button.text())
app = QApplication([])
calculator = Calculator()
calculator.show()
app.exec_()
To run this code, you'll need to install PyQt5 first:
pip install PyQt5
Kivy Example
Here's a similar calculator implementation using Kivy:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
class CalculatorApp(App):
def build(self):
self.operators = ["/", "*", "+", "-"]
self.last_was_operator = None
self.last_button = None
layout = BoxLayout(orientation='vertical')
self.solution = TextInput(
multiline=False, readonly=True, halign="right", font_size=55
)
layout.add_widget(self.solution)
buttons = [
["7", "8", "9", "/"],
["4", "5", "6", "*"],
["1", "2", "3", "-"],
[".", "0", "C", "+"],
]
for row in buttons:
h_layout = BoxLayout()
for label in row:
button = Button(
text=label,
pos=(0, 0),
size_hint=(1, 1),
)
button.bind(on_press=self.on_button_press)
h_layout.add_widget(button)
layout.add_widget(h_layout)
equals_button = Button(
text="=", pos=(0, 0), size_hint=(1, 1)
)
equals_button.bind(on_press=self.on_solution)
layout.add_widget(equals_button)
return layout
def on_button_press(self, instance):
current = self.solution.text
button_text = instance.text
if button_text == "C":
self.solution.text = ""
else:
if current and (
self.last_was_operator and button_text in self.operators):
return
elif current == "" and button_text in self.operators:
return
else:
new_text = current + button_text
self.solution.text = new_text
self.last_button = button_text
self.last_was_operator = self.last_button in self.operators
def on_solution(self, instance):
text = self.solution.text
if text:
try:
self.solution.text = str(eval(self.solution.text))
except Exception:
self.solution.text = "Error"
if __name__ == "__main__":
app = CalculatorApp()
app.run()
To run this code, you'll need to install Kivy first:
pip install kivy
PySimpleGUI Example
Here's a simple calculator implementation using PySimpleGUI:
import PySimpleGUI as sg
layout = [
[sg.Text('0', size=(16, 1), justification='right', key='-OUTPUT-', font=('Helvetica', 24))],
[sg.Button('7'), sg.Button('8'), sg.Button('9'), sg.Button('/')],
[sg.Button('4'), sg.Button('5'), sg.Button('6'), sg.Button('*')],
[sg.Button('1'), sg.Button('2'), sg.Button('3'), sg.Button('-')],
[sg.Button('0'), sg.Button('.'), sg.Button('C'), sg.Button('+')],
[sg.Button('=', size=(19, 1))]
]
window = sg.Window('PySimpleGUI Calculator', layout)
current_input = ""
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
if event in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.']:
current_input += event
window['-OUTPUT-'].update(current_input)
elif event in ['+', '-', '*', '/']:
current_input += event
window['-OUTPUT-'].update(current_input)
elif event == 'C':
current_input = ""
window['-OUTPUT-'].update('0')
elif event == '=':
try:
result = str(eval(current_input))
window['-OUTPUT-'].update(result)
current_input = result
except:
window['-OUTPUT-'].update('Error')
current_input = ""
window.close()
To run this code, you'll need to install PySimpleGUI first:
pip install pysimplegui
Comparison Table
Here's a comparison of the three frameworks:
| Framework | Ease of Use | Performance | Customization | Learning Curve |
|---|---|---|---|---|
| PyQt | Moderate | High | High | Moderate |
| Kivy | Moderate | High | High | Moderate |
| PySimpleGUI | Very High | Moderate | Moderate | Low |
FAQ
- Which framework should I choose for my Python GUI calculator?
- The best framework depends on your specific needs. PyQt offers the most professional look and feel, Kivy is great for touch interfaces, and PySimpleGUI is ideal for quick development with minimal code.
- Can I use these frameworks for commercial applications?
- Yes, all three frameworks can be used for commercial applications. PyQt and Kivy have commercial licenses available, while PySimpleGUI is open-source and free to use.
- Are there any alternatives to these frameworks?
- Yes, other alternatives include WxPython, Dear PyGui, and PySide (another Qt binding). Each has its own strengths and weaknesses depending on your project requirements.
- Can I create a calculator with a different layout using these frameworks?
- Absolutely! All three frameworks allow for extensive customization of the UI layout and design. You can create calculators with different button arrangements, themes, and additional features.