Hi, there
I recently found an interesting post that says “I made a Calculator with 17 lines of code”
Inspired by this, I tried to make a calculator using wxPython with minimal code.
First, the original code using Tkinter (slightly modified):
import tkinter as tk
def bt_draw(key, col, lin):
bt = tk.Button(window, text=key, command=lambda: bt_press(key), width=5)
bt.grid(column=col+1, row=lin+1)
return bt
def bt_press(key):
if key == 'C': disp['text'] = ''
elif key == '<': disp['text'] = disp['text'][:-1]
elif key == '=': disp['text'] = str(round(eval(disp['text']),16))
else : disp['text'] += key
window = tk.Tk()
window.title('Tkalc')
disp = tk.Label(window, text='')
disp.grid(column=0, row=0, columnspan=5)
keys = '()C<789/456*123-.0=+'
bt_list = [bt_draw(keys[n], n%4, n//4) for n in range(20)]
window.mainloop()
Second, using pySimpleGUI, it becomes 17 lines too.
import PySimpleGUI as sg
def bt_press(key):
text = window['display'].DisplayText
if key == 'C': text = ''
elif key == '<': text = text[:-1]
elif key == '=': text = str(round(eval(text),16))
else : text += key or ''
window['display'].update(text)
keys = '()C<789/456*123-.0=+'
layout = [[sg.Text(size=(40,1), key='display')]] +\
[[sg.Button(c, size=(5,-1)) for c in keys[i:i+4]] for i in range(0,20,4)]
window = sg.Window("sgcalc", layout)
while 1:
event, values = window.read()
bt_press(event)
if event == sg.WINDOW_CLOSED or event == 'Quit':
break
window.close()
Last of all, using wxPython, it came to 20 lines.
import wx
def pack(items, orient=wx.HORIZONTAL):
sizer = wx.BoxSizer(orient)
for item in items:
sizer.Add(item, 1, wx.EXPAND|wx.ALL, 0)
return sizer
def bt_press(key):
if key == 'C': disp.Value = ''
elif key == '<': disp.Value = disp.Value[:-1]
elif key == '=': disp.Value = str(round(eval(disp.Value),16))
else : disp.Value += key
app = wx.App()
self = wx.Frame(None, title="wxcalc")
keys = '()C<789/456*123-.0=+'
btns = [[wx.Button(self, label=c) for c in keys[i:i+4]] for i in range(0,20,4)]
disp = wx.TextCtrl(self)
self.Bind(wx.EVT_BUTTON, lambda v: bt_press(v.EventObject.Label))
self.SetSizer(pack([disp] + [pack(x) for x in btns], orient=wx.VERTICAL))
self.Show()
app.MainLoop()
The best I can do by for now…