Add math calculator to GUI

More
20 Aug 2021 20:23 - 20 Aug 2021 20:59 #218272 by aleksamc
I maid some GUI from tutorial some times ago.
There is  MDI tutorial

, where explained how to make some keyboard for mdi.

I would like in my GUI to add some functionality to such keyboard - to add math function buttons:
add, subtract, divide and mux.
Here is my python file.
 

File Attachment:

File Name: mainwindow...08-20.py
File Size:4 KB


There is functions
def WriteJogValue(self,button): if len(self.displayLabel.text()) >0: text = float(self.displayLabel.text()) if text > 0 or test <0: self.jogval.setValue(text) else: self.jogval.setValue(0) self.displayLabel.clear()

In such function I need to include such functionality for calculator:
self.displayLabel.text()[code] - is a text from screenwhere I need to get line:
567/2 (for example)
and to return back to this screen integer result: 283 or 285 or 283.5 (and in future programs to convert this float to integer)

How to make such thing?

I Think, I should do it with regular expressions:
[/code]
Af = re.match(r".*A\s*([\d\.,]+)", line)
In such example I find number after A and before space. It's hard to me to understand regular expressions. I don't understand them.
Attachments:
Last edit: 20 Aug 2021 20:59 by aleksamc.

Please Log in or Create an account to join the conversation.

More
21 Aug 2021 12:48 #218323 by BigJohnT
Replied by BigJohnT on topic Add math calculator to GUI
For simple equations you can use a function like this
#!/usr/bin/python3

def numeric(equation):
	if '+' in equation:
		y = equation.split('+')
		x = int(y[0])+int(y[1])
	elif '-' in equation:
		y = equation.split('-')
		x = int(y[0])-int(y[1])
	elif '/' in equation:
		y = equation.split('/')
		x = int(y[0])/int(y[1])
	elif '*' in equation:
		y = equation.split('*')
		x = int(y[0])*int(y[1])
	return x


test = input('Enter Simple Math ')
result = numeric(test)
print(result)

JT
The following user(s) said Thank You: aleksamc

Please Log in or Create an account to join the conversation.

More
21 Aug 2021 15:41 #218329 by aleksamc
Replied by aleksamc on topic Add math calculator to GUI
Thank you very mach, BigJohnT.
You helped me much.
Your program is very short and clear.

Please Log in or Create an account to join the conversation.

More
22 Aug 2021 12:09 #218408 by BigJohnT
Replied by BigJohnT on topic Add math calculator to GUI
A better example that works with negative numbers and floats and when the enter key is pressed it does the calculation.
#!/usr/bin/python3

import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLineEdit,
	QVBoxLayout, QLabel, QWidget, QFrame)
from PyQt5.QtGui import QIcon

class Window(QMainWindow):
	def __init__(self):
		super().__init__()
		self.setGeometry(50, 50, 350, 100) # X, Y, Width, Height
		self.setWindowTitle("PyQT5 Math Example!")

		central_widget = QWidget() # define central widget
		layout = QVBoxLayout() # define layout

		self.entry = QLineEdit()
		layout.addWidget(self.entry)

		self.lbl = QLabel(self)
		self.lbl.setFrameShape(QFrame.Box)
		self.lbl.setText('Enter a Simple Equation')
		layout.addWidget(self.lbl)

		central_widget.setLayout(layout) # add layout to central widget
		self.setCentralWidget(central_widget) # set QMainWindow layout

		# do the calc function when enter is pressed
		self.entry.returnPressed.connect(self.calc)

		self.show() # show the window

	def calc(self):
		equation = self.entry.text()
		if '+' in equation:
			y = equation.split('+')
			x = self.str2number(y[0])+self.str2number(y[1])
		elif '-' in equation:
			y = equation.split('-')
			x = self.str2number(y[0])-self.str2number(y[1])
		elif '/' in equation:
			y = equation.split('/')
			x = self.str2number(y[0])/self.str2number(y[1])
		elif '*' in equation:
			y = equation.split('*')
			x = self.str2number(y[0])*self.str2number(y[1])
		else:
			x = 'Invalid Equation'
		self.lbl.setText(str(x))

	def str2number(self, num):
		if num.isdigit():
			return int(num)
		elif num.startswith('-') and num[1:].isdigit():
			return int(num)
		else:
			return float(num)

if __name__ == '__main__':
	app = QApplication(sys.argv)
	GUI = Window()
	sys.exit(app.exec_())

JT

Please Log in or Create an account to join the conversation.

More
22 Aug 2021 12:10 #218409 by BigJohnT
Replied by BigJohnT on topic Add math calculator to GUI
Screenshot.
 

JT
Attachments:
The following user(s) said Thank You: tommylight

Please Log in or Create an account to join the conversation.

More
22 Aug 2021 18:05 #218420 by aleksamc
Replied by aleksamc on topic Add math calculator to GUI
I used your first example for calcs.

    def Calc(self, button):
        if len(self.displayLabel.text()) >0:
            equation = self.displayLabel.text()
            x=0
            if '+' in equation:
                y = equation.split('+')
                x = float(y[0])+float(y[1])
            elif '-' in equation:
                y = equation.split('-')
                x = float(y[0])-float(y[1])
            elif '/' in equation:
                y = equation.split('/')
                x = float(y[0])/float(y[1])
            elif '*' in equation:
                y = equation.split('*')
                x = float(y[0])*float(y[1])
            self.displayLabel.setNum(x)
 

For writing equation I use such function (from example)
    def numKeyboard(self, button):
        text = self.displayLabel.text() # copy the label text to the variable
        if len(text) > 0: # if there is something in the label
            text += button.text() # add the button text to the text variable
        else: # if the label is empty
            text = button.text() # assign the button text to the text variable
        self.displayLabel.setText(text) # set the text in label

"New forum editor is very good but return me back old one)))"
 

Please Log in or Create an account to join the conversation.

More
22 Aug 2021 20:31 #218436 by rodw
Replied by rodw on topic Add math calculator to GUI
Also look at the Python eval() statement to parse your input...
realpython.com/python-eval-function/
[code]>>> # Arithmetic operations
>>> eval("5 + 7")
12
>>> eval("5 * 7")
35
>>> eval("5 ** 7")
78125
>>> eval("(5 + 7) / 2")
6.0
>>> import math
>>> # Area of a circle
>>> eval("math.pi * pow(25, 2)")
1963.4954084936207
>>> # Volume of a sphere
>>> eval("4 / 3 * math.pi * math.pow(25, 3)")
65449.84694978735
>>> # Hypotenuse of a right triangle
>>> eval("math.sqrt(math.pow(10, 2) + math.pow(15, 2))")
18.027756377319946
[/code]
The following user(s) said Thank You: aleksamc

Please Log in or Create an account to join the conversation.

More
22 Aug 2021 20:42 #218437 by aleksamc
Replied by aleksamc on topic Add math calculator to GUI
Rodw, I currently try to solve such problem
I don't understand why logic statement
if (('+' or '-' or '*' or '/') in text) and ((button.text() == '+') or (button.text() == '-') or (button.text() == '*') or (button.text() == '/')):

works only partly like this:
if (('+' or '-' or '*' or '/') in text) and ((button.text() == '+') ....):

And you solve my problem complitly from other side!
The following user(s) said Thank You: rodw

Please Log in or Create an account to join the conversation.

More
22 Aug 2021 20:55 #218438 by BigJohnT
Replied by BigJohnT on topic Add math calculator to GUI
Just so you know eval() can be used for some bad things like wiping out your hard drive so use with caution.

JT
The following user(s) said Thank You: tommylight

Please Log in or Create an account to join the conversation.

More
23 Aug 2021 20:56 #218549 by rodw
Replied by rodw on topic Add math calculator to GUI

Just so you know eval() can be used for some bad things like wiping out your hard drive so use with caution.

JT

Well, you can guard against that
stackoverflow.com/questions/35804961/pyt...and-attribute-access

Please Log in or Create an account to join the conversation.

Moderators: KCJLcvette
Time to create page: 0.261 seconds
Powered by Kunena Forum