SoFunction
Updated on 2024-11-20

python tkinter A way to make a simple calculator

contexts

Recently, I've been learning python GUI, starting with tkinter, and I'd like to make a small piece of software to practice with.
Thinking about it, I decided to make a calculator.

Design Ideas

First, import the package we need - tkinter and create the window by instantiating a Tk object
Since I'm a bit of a novice and can't control the placement of the components well at the moment, I'm using the automatic default size for the window.

import tkinter as tk
import 
win = ()
("Calculator.")
()

Plan the location of the components in a general way

My goal is to make it look like this (final result)

After roughly mapping out the locations, I created four frames, as follows
u1s1, it feels like two or three is enough

# Frames that host prompts and input boxes
entry_frame = (win)
# Frames to carry the operator symbols
menu_frame = (win)
# Frames that carry the numbers
major_frame = (win)
# Frames that carry the equals sign
cal_frame = (win)

entry_frame.pack(side="top")
menu_frame.pack(side="left")
major_frame.pack()
cal_frame.pack(side="right")

Here's how to make an input box, divided into two parts

  • One part is the Chinese character part, prompting for information, using the Label control.
  • One part is an input box, using the Entry control.
t_label = (entry_frame, text = "Please enter : ")
t_label.pack(side='left')
word_entry = (
    entry_frame,
    fg = "blue", # Enter the font color, set to blue
    bd = 3, # Border width
    width = 39, # Input box length
    justify = 'right' # Set alignment to right
)
word_entry.pack()

Then line up the symbols on the left-hand side below.

for char in ['+', '-', '×', '÷']:
    myButton(menu_frame, char, word_entry)

In this case, the myButton class instantiates a button, and when the button is clicked, the corresponding text appears in the input box
I had a problem at the time - clicking on the button did not get the text on the button you were fighting for, and after solving the problem I wrote a blog post about it.portal

List the numbers in the same way

for i in range(4):
    num_frame = (major_frame)
    num_frame.pack()
    if i < 3:
        for count in range(3*i+1, 3*i+4):
            myButton(num_frame, count, word_entry, side=(i, count))
        continue
    myButton(num_frame, 0, word_entry, side=(i, 0))

Of course, you can't forget the reset button and the calculate button.
The final calculation is a bit lazy, directly use () to get the formula to be calculated, use the eval() function to calculate, if the format is wrong that is, the pop-up window prompts

def calculate(entry):
    try:
        result = ()
        # If no string exists in the input box, the = button doesn't work
        if result == '':
            return
        result = eval(result)
        (0, "end")
        (0, str(result))
    except:
        ("Error.", "Formatting error! \n Please re-enter!")
reset_btn = (
    cal_frame,
    text = 'Reset',
    activeforeground = "blue",
    activebackground = "pink",
    width = "13",
    command = lambda :word_entry.delete(0, "end")
).pack(side="left")
result_btn = (
    cal_frame,
    text = '=',
    activeforeground = "blue",
    activebackground = "pink",
    width = "13",
    command = lambda :calculate(word_entry)
).pack(side="right")

All Codes


# -*- coding=utf-8 -*-
# @Time    : 2021/3/4 13:06
# @Author  : lhys
# @FileName: 

myName = r'''
    Welcome, my master!
    My Name is :
     ____                ____        ____        ____         ____              ______________
    |    |              |    |      |    |      |    \       /    |           /              /
    |    |              |    |      |    |      |     \     /     |          /              /
    |    |              |    |      |    |      |      \   /      |         /              /
    |    |              |    |      |    |       \      \_/      /         /       _______/
    |    |              |    |______|    |        \             /          \            \
    |    |              |                |         \           /            \            \
    |    |              |     ______     |          \         /              \            \
    |    |              |    |      |    |           \       /                \________    \
    |    |              |    |      |    |            |     |               /              /
    |    |_______       |    |      |    |            |     |              /              /
    |            |      |    |      |    |            |     |             /              /
    |____________|      |____|      |____|            |_____|            /______________/
    '''
print(myName)
import tkinter as tk
from tools import *

win = ()
('Calculator')

entry_frame = (win)
menu_frame = (win)
major_frame = (win)
cal_frame = (win)

entry_frame.pack(side="top")
menu_frame.pack(side="left")
major_frame.pack()
cal_frame.pack()

# Input box
t_label = (entry_frame, text = "Please enter : ")
t_label.pack(side='left')
word_entry = (
    entry_frame,
    fg = "blue",
    bd = 3,
    width = 39,
    justify = 'right'
)
word_entry.pack()


# Menu bar
for char in ['+', '-', '×', '÷']:
    myButton(menu_frame, char, word_entry)

button_side = ['right', 'left']

for i in range(4):
    num_frame = (major_frame)
    num_frame.pack()
    if i < 3:
        for count in range(3*i+1, 3*i+4):
            myButton(num_frame, count, word_entry, side=(i, count))
        continue
    myButton(num_frame, 0, word_entry, side=(i, 0))

reset_btn = (
    cal_frame,
    text = 'Reset',
    activeforeground = "blue",
    activebackground = "pink",
    width = "13",
    command = lambda :word_entry.delete(0, "end")
).pack(side="left")
result_btn = (
    cal_frame,
    text = '=',
    activeforeground = "blue",
    activebackground = "pink",
    width = "13",
    command = lambda :calculate(word_entry)
).pack(side="right")

()


# -*- coding=utf-8 -*-
# @Time    : 2021/3/4 13:20
# @Author  : lhys
# @FileName: 

import tkinter
import 

def calculate(entry):
    try:
        result = ()
        if result == '':
            return
        result = eval(result)
        print(result)
        (0, "end")
        (0, str(result))
    except:
        ("Error.", "Formatting error! \n Please re-enter!")

class myButton():
    def __init__(self, frame, text, entry, **kwargs):
        side = ('side') if 'side' in kwargs else ()
         = (
            frame,
            text = text,
            activeforeground="blue",
            activebackground="pink",
            width="13",
            command=lambda :("end", text)
        )
        if side:
            (row=side[0], column=side[1])
        else:
            ()

to this article on python tkinter do a simple calculator of the method of the article is introduced to this, more related python tkinter calculator content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!