为什么要实现矩阵计算器?
答:因为可以带来便利,相当于把matlib中对矩阵的基本操作抽离出来,降低操作门槛,同时也更加灵活自由,代码可以自己控制,功能可以自己添加修改。
–参考了pyqt5的example中的calculator。有关矩阵的库主要使用了sympy,参考了大佬的博客:sympy矩阵操作。
计算器样子,丑媳妇早晚要见大大们, 后续我学好了qss和style 再优化它~/滑稽/逃:
言归正传,输入,输出格式举例(转置):
一些想法:
1.实现计算器之前可以先在https://www.draw.io/上绘制模型,这样布局的时候会更有底气,如:
2.如果想要把他变成exe,先
pip install pyinstaller
然后:
pyinstaller -F -w -p /d/software/python3.7.4/lib calc.py
-F是生产单个文件,-w是图像界面显示(注意:需要在windows下),-p指出python lib的位置
之后运行会报错,没事不慌,
打开生产的 calc.spec,在第二、三行插入
import sys
sys.setrecursionlimit(5000)
最后:
pyinstaller calc.spec
就在dist文件夹下生产了calc.exe
矩阵计算器代码:
#!/usr/bin/python3
# -*- encoding_utf-8 -*-
import sys
sys.setrecursionlimit(5000) #为了用pyinstaller生产exe添加
if hasattr(sys, 'frozen'): #为了生产exe添加
os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']
from PyQt5.QtWidgets import (QToolButton, QFrame, QVBoxLayout, QHBoxLayout, QGridLayout,
QApplication, QTextEdit, QSizePolicy, QLineEdit)
from PyQt5.QtGui import QIntValidator, QTextOption, QTextCursor
from sympy import symbols, Matrix, solve, diff, eye
class Button(QToolButton):
def __init__(self, text, parent=None):
super(Button, self).__init__(parent)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
self.setText(text)
def sizeHint(self):
size = super(Button, self).sizeHint()
size.setHeight(size.height() + 50)
size.setWidth(max(size.width(), size.height()))
return size
class Calc(QFrame):
NumDigitButtons = 10
def __init__(self):
super().__init__()
self.initData()
self.initUI()
self.initConnect()
def initData(self):
pass
def initUI(self):
self.layout = QVBoxLayout()
self.createDisplayBox()
self.createInputBox()
self.setLayout(self.layout)
self.show()
def initConnect(self):
self.input.textChanged.connect(self.cursorChange)
def cursorChange(self):
print('cursorChange')
cursor = self.input.textCursor()
cursor.movePosition(QTextCursor.End)
self.input.setTextCursor(cursor)
def createDisplayBox(self):
layout = QHBoxLayout()
self.input = QTextEdit()
self.output = QTextEdit()
self.output.setReadOnly(True)
self.output.setWordWrapMode(QTextOption.NoWrap)
layout.addWidget(self.input)
layout.addWidget(self.output)
layout.setStretch(1.5, 1)
self.layout.addLayout(layout)
def createInputBox(self):
layout = QGridLayout()
self.digitButtons = []
for i in range(Calc.NumDigitButtons):
self.digitButtons.append(self.createButton(str(i),
self.digitClicked))
self.reverseButton = self.createButton("求逆",
self.reverseOperateClicked)
self.powButton = self.createButton("次方:",
self.powOperatorClicked)
self.powLineEdit = QLineEdit