也希望大家多多支持脚本之家9159.com,目前可以实

作者: 编程  发布:2019-09-02

python3.5 PyQt5 Eric6 实现的一个计算器,pyqt5eric6

目前可以实现简单的计算。计算前请重置,设计的时候默认数字是0,
学了半天就做出来个这么个结果,bug不少。 python3.5 PyQt5 Eric6 在windows7 32位系统可以完美运行 计算器,简单学了半天就画个图实现的存在bug,部分按钮还未实现,后续优化。

代码结构如图:

 9159.com 1

 1 jisuan.py
 2 import re
 3 #匹配整数或小数的乘除法,包括了开头存在减号的情况
 4 mul_div=re.compile("(-?d )(.d )?(*|/)(-?d )(.d )?")
 5 #匹配整数或小数的加减法,包括了开头存在减号的情况
 6 plus_minus = re.compile("(-?d )(.d )?(-| )(-?d )(.d )?")
 7 #匹配括号
 8 bracket=re.compile("([^()]*)")
 9 #匹配乘法的时候出现乘以负数的情况,包括了开头存在减号的情况
10 mul_minus_minus = re.compile("(-?d )(.d )?(*-)(d )(.d )?")
11 #匹配除法的时候出现乘以负数的情况,包括了开头存在减号的情况
12 div_minus_minus = re.compile("(-?d )(.d )?(/-)(d )(.d )?")
13 #定义一个两位数的加减乘除法的运算,匹配左边的右边的数字和左边的数字,然后进行计算
14 def touble_cale(str_expire):
15     if str_expire.count(" ") == 1:
16         right_num = float(str_expire[(str_expire.find(" ") 1):])
17         left_num = float(str_expire[:str_expire.find(" ")])
18         return str(right_num left_num)
19     elif str_expire[1:].count("-") == 1:
20         right_num = float(str_expire[:str_expire.find("-",1)])
21         left_num = float(str_expire[(str_expire.find("-", 1)   1):])
22         return str(right_num - left_num)
23     elif str_expire.count("*") == 1:
24         right_num = float(str_expire[:str_expire.find("*")])
25         left_num = float(str_expire[(str_expire.find("*") 1):])
26         return str(right_num * left_num)
27     elif str_expire.count("/") == 1:
28         right_num = float(str_expire[:str_expire.find("/")])
29         left_num = float(str_expire[(str_expire.find("/")   1):])
30         return str(right_num / left_num)
31 
32 
33 #定义一个方法用于判断是否存在乘以负数和除以负数的情况
34 def judge_mul_minus(str_expire):
35     #判断公式中乘以负数的部分
36     if len(re.findall("(*-)", str_expire)) != 0:
37         #调用上面的正则取得*-的公式
38         temp_mul_minus = mul_minus_minus.search(str_expire).group()
39         #将匹配的部分的*-换成*并将-放到前面
40         temp_mul_minus_2 = temp_mul_minus.replace(temp_mul_minus,"-"   temp_mul_minus.replace("*-","*"))
41         #经更改的的部分与原来的部分进行替换
42         str_expire=str_expire.replace(temp_mul_minus,temp_mul_minus_2)
43         return judge_mul_minus(str_expire)
44         #return str_expire
45     # 判断公式中除以负数的部分
46     elif len(re.findall(r"(/-)", str_expire)) != 0:
47         # 调用上面的正则取得/-的公式
48         temp_dev_minus = div_minus_minus.search(str_expire).group()
49         # 将匹配的部分的/-换成/并将-放到前面
50         temp_dev_minus_2 = temp_dev_minus.replace(temp_dev_minus,"-"   temp_dev_minus.replace("/-","/"))
51         # 经更改的的部分与原来的部分进行替换
52         str_expire = str_expire.replace(temp_dev_minus,temp_dev_minus_2)
53         return judge_mul_minus(str_expire)
54     #调用change_sign将公式中的  换成=  -换成-
55     return change_sign(str_expire)
56 
57 #定义一个方法取将--更改为   -改为-
58 def change_sign(str_expire):
59     if len(re.findall(r"( -)", str_expire)) != 0:
60         str_expire = str_expire.replace(" -", "-")
61         return change_sign(str_expire)
62     elif len(re.findall(r"(--)", str_expire)) != 0:
63         str_expire = str_expire.replace("--", " ")
64         return change_sign(str_expire)
65     return str_expire
66 
67 
68 #定义一个方法用于计算只有加减乘除的公式,优先处理乘法
69 def cale_mix(str_expire):
70     #如果公式中出现符号数字的情况即 5  -6 *8  /8的这种情况直接放回数字否则则先计算乘除在处理加减
71     while len(re.findall("[- */]",str_expire[1:])) != 0:
72         if len(re.findall("(*|/)",str_expire)) != 0:
73             str_expire = str_expire.replace(mul_div.search(str_expire).group(),touble_cale(mul_div.search(str_expire).group()))
74         elif len(re.findall("( |-)",str_expire)) !=0:
75             str_expire = str_expire.replace(plus_minus.search(str_expire).group(),touble_cale(plus_minus.search(str_expire).group()))
76     return str_expire
77 
78 #定义一个方法用于去括号,并调用上述的方法进行计算
79 def remove_bracket(str_expire):
80     #判断公式中是否有括号
81     if len(bracket.findall(str_expire)) == 0:
82         return cale_mix(judge_mul_minus(str_expire))
83     elif len(bracket.findall(str_expire))!=0:
84         while len(bracket.findall(str_expire)) !=0:
85             #print(bracket.search(str_expire).group())
86             #只有存在括号优先处理括号中的内容并对内容进行替换,直到没有括号位置
87             str_expire = str_expire.replace(bracket.search(str_expire).group(),cale_mix(judge_mul_minus(bracket.search(str_expire).group()[1:-1])))
88         str_expire = cale_mix(judge_mul_minus(str_expire))
89         return str_expire
90 if __name__ == "__main__":
91     while True:
92         user_input_expire = input("请输入你的公式:(不要带空格,q表示退出):")
93         print("%s=%s" %(user_input_expire,remove_bracket(user_input_expire)))
94         continue

untitled.py
# -*- coding: utf-8 -*-
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui, QtWidgets
from Ui_untitled import Ui_Dialog
from jisuan import remove_bracket
class Dialog(QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setupUi(self)
    @pyqtSlot()
    def on_Button_6_clicked(self):
        self.Edit_xianshi.insertPlainText('6')
    @pyqtSlot()
    def on_Button_2_clicked(self):
        self.Edit_xianshi.insertPlainText('2')
    @pyqtSlot()
    def on_Button_3_clicked(self):
        self.Edit_xianshi.insertPlainText('3')
    @pyqtSlot()
    def on_Button_pingfang_clicked(self):
        me=self.Edit_xianshi.toPlainText()
        m=int(me) *int(me)
        self.Edit_xianshi.clear()
        self.Edit_xianshi.append(str(m))
    @pyqtSlot()
    def on_Button_add_clicked(self):
        h=self.Edit_xianshi.toPlainText()
        self.Edit_xianshi.clear()
        self.Edit_xianshi.append(h ' ')
    @pyqtSlot()
    def on_Button_jian_clicked(self):
        h = self.Edit_xianshi.toPlainText()
        self.Edit_xianshi.clear()
        self.Edit_xianshi.append(h   '-')
    @pyqtSlot()
    def on_Button_9_clicked(self):
        self.Edit_xianshi.insertPlainText('9')
    @pyqtSlot()
    def on_Button_chu_clicked(self):
        h = self.Edit_xianshi.toPlainText()
        self.Edit_xianshi.clear()
        self.Edit_xianshi.append(h   '/')
    @pyqtSlot()
    def on_Button_cheng_clicked(self):
        h = self.Edit_xianshi.toPlainText()
        self.Edit_xianshi.clear()
        self.Edit_xianshi.append(h   '*')
    @pyqtSlot()
    def on_Button_8_clicked(self):
        self.Edit_xianshi.insertPlainText('8')
    @pyqtSlot()
    def on_Button_4_clicked(self):
        self.Edit_xianshi.insertPlainText('4')
    @pyqtSlot()
    def on_Button_esc_clicked(self):
        self.Edit_xianshi.clear()
    @pyqtSlot()
    def on_Button_7_clicked(self):
        self.Edit_xianshi.insertPlainText('7')
    @pyqtSlot()
    def on_Button_1_clicked(self):
        self.Edit_xianshi.insertPlainText('1')
    @pyqtSlot()
    def on_Button_5_clicked(self):
        self.Edit_xianshi.insertPlainText('5')
    @pyqtSlot()
    def on_Button_xiaoshu_clicked(self):
        self.Edit_xianshi.insertPlainText('.')
    @pyqtSlot()
    def on_Button_0_clicked(self):
        self.Edit_xianshi.insertPlainText('0')
    @pyqtSlot()
    def on_Button_dengyu_clicked(self):
        pe=self.Edit_xianshi.toPlainText()
        m=remove_bracket(pe)
        self.Edit_xianshi.clear()
        self.Edit_xianshi.append(str(m))

    def on_Button_fenzhi_clicked(self):
        pe = self.Edit_xianshi.toPlainText()
        if int(pe) ==0:
            QMessageBox.information(self,u'提示',u'零不能作为分母')
            Dialog()
        else:
            m=1/(int(pe))
            self.Edit_xianshi.clear()
            self.Edit_xianshi.append(str(m))
            Dialog()
if __name__ =="__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    app.processEvents()
    ui = Dialog()
    ui.show()

    sys.exit(app.exec_())

Ui_untitled.py
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'C:UsersAdministratorDesktoppyqt5untitled.ui'
#
# Created by: PyQt5 UI code generator 5.5
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(357, 320)
        Dialog.setStyleSheet("font: 75 16pt "Aharoni";n"
"background-color: rgb(206, 255, 251);")
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(201, 210, 301, 21))
        self.label.setText("")
        self.label.setObjectName("label")
        self.Edit_xianshi = QtWidgets.QTextEdit(Dialog)
        self.Edit_xianshi.setGeometry(QtCore.QRect(0, 0, 351, 41))
        self.Edit_xianshi.setStyleSheet("font: 75 16pt "Aharoni";")
        self.Edit_xianshi.setObjectName("Edit_xianshi")
        self.gridLayoutWidget = QtWidgets.QWidget(Dialog)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(0, 30, 351, 281))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setObjectName("gridLayout")
        self.Button_6 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_6.setObjectName("Button_6")
        self.gridLayout.addWidget(self.Button_6, 2, 2, 1, 1)
        self.Button_2 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_2.setObjectName("Button_2")
        self.gridLayout.addWidget(self.Button_2, 3, 1, 1, 1)
        self.Button_3 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_3.setObjectName("Button_3")
        self.gridLayout.addWidget(self.Button_3, 3, 2, 1, 1)
        self.Button_fenzhi = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_fenzhi.setObjectName("Button_fenzhi")
        self.gridLayout.addWidget(self.Button_fenzhi, 1, 3, 1, 1)
        self.Button_pingfang = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_pingfang.setObjectName("Button_pingfang")
        self.gridLayout.addWidget(self.Button_pingfang, 0, 3, 1, 1)
        self.Button_add = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_add.setObjectName("Button_add")
        self.gridLayout.addWidget(self.Button_add, 2, 3, 1, 1)
        self.Button_jian = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_jian.setObjectName("Button_jian")
        self.gridLayout.addWidget(self.Button_jian, 3, 3, 1, 1)
        self.Button_9 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_9.setObjectName("Button_9")
        self.gridLayout.addWidget(self.Button_9, 1, 2, 1, 1)
        self.Button_chu = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_chu.setObjectName("Button_chu")
        self.gridLayout.addWidget(self.Button_chu, 0, 2, 1, 1)
        self.Button_cheng = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_cheng.setObjectName("Button_cheng")
        self.gridLayout.addWidget(self.Button_cheng, 0, 1, 1, 1)
        self.Button_8 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_8.setObjectName("Button_8")
        self.gridLayout.addWidget(self.Button_8, 1, 1, 1, 1)
        self.Button_4 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_4.setObjectName("Button_4")
        self.gridLayout.addWidget(self.Button_4, 2, 0, 1, 1)
        self.Button_esc = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_esc.setObjectName("Button_esc")
        self.gridLayout.addWidget(self.Button_esc, 0, 0, 1, 1)
        self.Button_7 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_7.setObjectName("Button_7")
        self.gridLayout.addWidget(self.Button_7, 1, 0, 1, 1)
        self.Button_1 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_1.setObjectName("Button_1")
        self.gridLayout.addWidget(self.Button_1, 3, 0, 1, 1)
        self.Button_5 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_5.setObjectName("Button_5")
        self.gridLayout.addWidget(self.Button_5, 2, 1, 1, 1)
        self.pushButton_17 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.pushButton_17.setText("")
        self.pushButton_17.setObjectName("pushButton_17")
        self.gridLayout.addWidget(self.pushButton_17, 4, 0, 1, 1)
        self.Button_xiaoshu = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_xiaoshu.setObjectName("Button_xiaoshu")
        self.gridLayout.addWidget(self.Button_xiaoshu, 4, 1, 1, 1)
        self.Button_0 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_0.setStyleSheet("")
        self.Button_0.setObjectName("Button_0")
        self.gridLayout.addWidget(self.Button_0, 4, 2, 1, 1)
        self.Button_dengyu = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_dengyu.setObjectName("Button_dengyu")
        self.gridLayout.addWidget(self.Button_dengyu, 4, 3, 1, 1)

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.Edit_xianshi.setHtml(_translate("Dialog", "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">n"
"<html><head><meta name="qrichtext" content="1" /><style type="text/css">n"
"p, li { white-space: pre-wrap; }n"
"</style></head><body style=" font-family:'Aharoni'; font-size:16pt; font-weight:72; font-style:normal;">n"
"<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">0</p></body></html>"))
        self.Button_6.setText(_translate("Dialog", "6"))
        self.Button_2.setText(_translate("Dialog", "2"))
        self.Button_3.setText(_translate("Dialog", "3"))
        self.Button_fenzhi.setText(_translate("Dialog", "1/^"))
        self.Button_pingfang.setText(_translate("Dialog", "^2"))
        self.Button_add.setText(_translate("Dialog", " "))
        self.Button_jian.setText(_translate("Dialog", "-"))
        self.Button_9.setText(_translate("Dialog", "9"))
        self.Button_chu.setText(_translate("Dialog", "/"))
        self.Button_cheng.setText(_translate("Dialog", "*"))
        self.Button_8.setText(_translate("Dialog", "8"))
        self.Button_4.setText(_translate("Dialog", "4"))
        self.Button_esc.setText(_translate("Dialog", "esc"))
        self.Button_7.setText(_translate("Dialog", "7"))
        self.Button_1.setText(_translate("Dialog", "1"))
        self.Button_5.setText(_translate("Dialog", "5"))
        self.Button_xiaoshu.setText(_translate("Dialog", "."))
        self.Button_0.setText(_translate("Dialog", "0"))
        self.Button_dengyu.setText(_translate("Dialog", "="))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

 

 

 

 

 

 

效果图:

9159.com 2

 github 传送门

PyQt5 Eric6 实现的一个计算器,pyqt5eric6 目前可以实现简单的计算。计算前请重置,设计的时候默认数字是0, 学了半天就做出来个...

python3.5 PyQt5 Eric6 实现的一个计算器代码,pyqt5eric6

目前可以实现简单的计算。计算前请重置,设计的时候默认数字是0,学了半天就做出来个这么个结果,bug不少。 python3.5 PyQt5 Eric6 在windows7 32位系统可以完美运行 计算器,简单学了半天就画个图实现的存在bug,部分按钮还未实现,后续优化。

代码结构如图:

9159.com 3 

jisuan.py

import re
#匹配整数或小数的乘除法,包括了开头存在减号的情况
mul_div=re.compile("(-?d )(.d )?(*|/)(-?d )(.d )?")
#匹配整数或小数的加减法,包括了开头存在减号的情况
plus_minus = re.compile("(-?d )(.d )?(-| )(-?d )(.d )?")
#匹配括号
bracket=re.compile("([^()]*)")
#匹配乘法的时候出现乘以负数的情况,包括了开头存在减号的情况
mul_minus_minus = re.compile("(-?d )(.d )?(*-)(d )(.d )?")
#匹配除法的时候出现乘以负数的情况,包括了开头存在减号的情况
div_minus_minus = re.compile("(-?d )(.d )?(/-)(d )(.d )?")
#定义一个两位数的加减乘除法的运算,匹配左边的右边的数字和左边的数字,然后进行计算
def touble_cale(str_expire):
  if str_expire.count(" ") == 1:
    right_num = float(str_expire[(str_expire.find(" ") 1):])
    left_num = float(str_expire[:str_expire.find(" ")])
    return str(right_num left_num)
  elif str_expire[1:].count("-") == 1:
    right_num = float(str_expire[:str_expire.find("-",1)])
    left_num = float(str_expire[(str_expire.find("-", 1)   1):])
    return str(right_num - left_num)
  elif str_expire.count("*") == 1:
    right_num = float(str_expire[:str_expire.find("*")])
    left_num = float(str_expire[(str_expire.find("*") 1):])
    return str(right_num * left_num)
  elif str_expire.count("/") == 1:
    right_num = float(str_expire[:str_expire.find("/")])
    left_num = float(str_expire[(str_expire.find("/")   1):])
    return str(right_num / left_num)


#定义一个方法用于判断是否存在乘以负数和除以负数的情况
def judge_mul_minus(str_expire):
  #判断公式中乘以负数的部分
  if len(re.findall("(*-)", str_expire)) != 0:
    #调用上面的正则取得*-的公式
    temp_mul_minus = mul_minus_minus.search(str_expire).group()
    #将匹配的部分的*-换成*并将-放到前面
    temp_mul_minus_2 = temp_mul_minus.replace(temp_mul_minus,"-"   temp_mul_minus.replace("*-","*"))
    #经更改的的部分与原来的部分进行替换
    str_expire=str_expire.replace(temp_mul_minus,temp_mul_minus_2)
    return judge_mul_minus(str_expire)
    #return str_expire
  # 判断公式中除以负数的部分
  elif len(re.findall(r"(/-)", str_expire)) != 0:
    # 调用上面的正则取得/-的公式
    temp_dev_minus = div_minus_minus.search(str_expire).group()
    # 将匹配的部分的/-换成/并将-放到前面
    temp_dev_minus_2 = temp_dev_minus.replace(temp_dev_minus,"-"   temp_dev_minus.replace("/-","/"))
    # 经更改的的部分与原来的部分进行替换
    str_expire = str_expire.replace(temp_dev_minus,temp_dev_minus_2)
    return judge_mul_minus(str_expire)
  #调用change_sign将公式中的  换成=  -换成-
  return change_sign(str_expire)

#定义一个方法取将--更改为   -改为-
def change_sign(str_expire):
  if len(re.findall(r"( -)", str_expire)) != 0:
    str_expire = str_expire.replace(" -", "-")
    return change_sign(str_expire)
  elif len(re.findall(r"(--)", str_expire)) != 0:
    str_expire = str_expire.replace("--", " ")
    return change_sign(str_expire)
  return str_expire


#定义一个方法用于计算只有加减乘除的公式,优先处理乘法
def cale_mix(str_expire):
  #如果公式中出现符号数字的情况即 5 -6 *8 /8的这种情况直接放回数字否则则先计算乘除在处理加减
  while len(re.findall("[- */]",str_expire[1:])) != 0:
    if len(re.findall("(*|/)",str_expire)) != 0:
      str_expire = str_expire.replace(mul_div.search(str_expire).group(),touble_cale(mul_div.search(str_expire).group()))
    elif len(re.findall("( |-)",str_expire)) !=0:
      str_expire = str_expire.replace(plus_minus.search(str_expire).group(),touble_cale(plus_minus.search(str_expire).group()))
  return str_expire

#定义一个方法用于去括号,并调用上述的方法进行计算
def remove_bracket(str_expire):
  #判断公式中是否有括号
  if len(bracket.findall(str_expire)) == 0:
    return cale_mix(judge_mul_minus(str_expire))
  elif len(bracket.findall(str_expire))!=0:
    while len(bracket.findall(str_expire)) !=0:
      #print(bracket.search(str_expire).group())
      #只有存在括号优先处理括号中的内容并对内容进行替换,直到没有括号位置
      str_expire = str_expire.replace(bracket.search(str_expire).group(),cale_mix(judge_mul_minus(bracket.search(str_expire).group()[1:-1])))
    str_expire = cale_mix(judge_mul_minus(str_expire))
    return str_expire
if __name__ == "__main__":
  while True:
    user_input_expire = input("请输入你的公式:(不要带空格,q表示退出):")
    print("%s=%s" %(user_input_expire,remove_bracket(user_input_expire)))
    continue

untitled.py

# -*- coding: utf-8 -*-
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui, QtWidgets
from Ui_untitled import Ui_Dialog
from jisuan import remove_bracket
class Dialog(QDialog, Ui_Dialog):
  def __init__(self, parent=None):
    super(Dialog, self).__init__(parent)
    self.setupUi(self)
  @pyqtSlot()
  def on_Button_6_clicked(self):
    self.Edit_xianshi.insertPlainText('6')
  @pyqtSlot()
  def on_Button_2_clicked(self):
    self.Edit_xianshi.insertPlainText('2')
  @pyqtSlot()
  def on_Button_3_clicked(self):
    self.Edit_xianshi.insertPlainText('3')
  @pyqtSlot()
  def on_Button_pingfang_clicked(self):
    me=self.Edit_xianshi.toPlainText()
    m=int(me) *int(me)
    self.Edit_xianshi.clear()
    self.Edit_xianshi.append(str(m))
  @pyqtSlot()
  def on_Button_add_clicked(self):
    h=self.Edit_xianshi.toPlainText()
    self.Edit_xianshi.clear()
    self.Edit_xianshi.append(h ' ')
  @pyqtSlot()
  def on_Button_jian_clicked(self):
    h = self.Edit_xianshi.toPlainText()
    self.Edit_xianshi.clear()
    self.Edit_xianshi.append(h   '-')
  @pyqtSlot()
  def on_Button_9_clicked(self):
    self.Edit_xianshi.insertPlainText('9')
  @pyqtSlot()
  def on_Button_chu_clicked(self):
    h = self.Edit_xianshi.toPlainText()
    self.Edit_xianshi.clear()
    self.Edit_xianshi.append(h   '/')
  @pyqtSlot()
  def on_Button_cheng_clicked(self):
    h = self.Edit_xianshi.toPlainText()
    self.Edit_xianshi.clear()
    self.Edit_xianshi.append(h   '*')
  @pyqtSlot()
  def on_Button_8_clicked(self):
    self.Edit_xianshi.insertPlainText('8')
  @pyqtSlot()
  def on_Button_4_clicked(self):
    self.Edit_xianshi.insertPlainText('4')
  @pyqtSlot()
  def on_Button_esc_clicked(self):
    self.Edit_xianshi.clear()
  @pyqtSlot()
  def on_Button_7_clicked(self):
    self.Edit_xianshi.insertPlainText('7')
  @pyqtSlot()
  def on_Button_1_clicked(self):
    self.Edit_xianshi.insertPlainText('1')
  @pyqtSlot()
  def on_Button_5_clicked(self):
    self.Edit_xianshi.insertPlainText('5')
  @pyqtSlot()
  def on_Button_xiaoshu_clicked(self):
    self.Edit_xianshi.insertPlainText('.')
  @pyqtSlot()
  def on_Button_0_clicked(self):
    self.Edit_xianshi.insertPlainText('0')
  @pyqtSlot()
  def on_Button_dengyu_clicked(self):
    pe=self.Edit_xianshi.toPlainText()
    m=remove_bracket(pe)
    self.Edit_xianshi.clear()
    self.Edit_xianshi.append(str(m))

  def on_Button_fenzhi_clicked(self):
    pe = self.Edit_xianshi.toPlainText()
    if int(pe) ==0:
      QMessageBox.information(self,u'提示',u'零不能作为分母')
      Dialog()
    else:
      m=1/(int(pe))
      self.Edit_xianshi.clear()
      self.Edit_xianshi.append(str(m))
      Dialog()
if __name__ =="__main__":
  import sys
  app = QtWidgets.QApplication(sys.argv)
  app.processEvents()
  ui = Dialog()
  ui.show()

  sys.exit(app.exec_())

Ui_untitled.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'C:UsersAdministratorDesktoppyqt5untitled.ui'
#
# Created by: PyQt5 UI code generator 5.5
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
  def setupUi(self, Dialog):
    Dialog.setObjectName("Dialog")
    Dialog.resize(357, 320)
    Dialog.setStyleSheet("font: 75 16pt "Aharoni";n"
"background-color: rgb(206, 255, 251);")
    self.label = QtWidgets.QLabel(Dialog)
    self.label.setGeometry(QtCore.QRect(201, 210, 301, 21))
    self.label.setText("")
    self.label.setObjectName("label")
    self.Edit_xianshi = QtWidgets.QTextEdit(Dialog)
    self.Edit_xianshi.setGeometry(QtCore.QRect(0, 0, 351, 41))
    self.Edit_xianshi.setStyleSheet("font: 75 16pt "Aharoni";")
    self.Edit_xianshi.setObjectName("Edit_xianshi")
    self.gridLayoutWidget = QtWidgets.QWidget(Dialog)
    self.gridLayoutWidget.setGeometry(QtCore.QRect(0, 30, 351, 281))
    self.gridLayoutWidget.setObjectName("gridLayoutWidget")
    self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
    self.gridLayout.setObjectName("gridLayout")
    self.Button_6 = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_6.setObjectName("Button_6")
    self.gridLayout.addWidget(self.Button_6, 2, 2, 1, 1)
    self.Button_2 = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_2.setObjectName("Button_2")
    self.gridLayout.addWidget(self.Button_2, 3, 1, 1, 1)
    self.Button_3 = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_3.setObjectName("Button_3")
    self.gridLayout.addWidget(self.Button_3, 3, 2, 1, 1)
    self.Button_fenzhi = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_fenzhi.setObjectName("Button_fenzhi")
    self.gridLayout.addWidget(self.Button_fenzhi, 1, 3, 1, 1)
    self.Button_pingfang = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_pingfang.setObjectName("Button_pingfang")
    self.gridLayout.addWidget(self.Button_pingfang, 0, 3, 1, 1)
    self.Button_add = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_add.setObjectName("Button_add")
    self.gridLayout.addWidget(self.Button_add, 2, 3, 1, 1)
    self.Button_jian = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_jian.setObjectName("Button_jian")
    self.gridLayout.addWidget(self.Button_jian, 3, 3, 1, 1)
    self.Button_9 = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_9.setObjectName("Button_9")
    self.gridLayout.addWidget(self.Button_9, 1, 2, 1, 1)
    self.Button_chu = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_chu.setObjectName("Button_chu")
    self.gridLayout.addWidget(self.Button_chu, 0, 2, 1, 1)
    self.Button_cheng = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_cheng.setObjectName("Button_cheng")
    self.gridLayout.addWidget(self.Button_cheng, 0, 1, 1, 1)
    self.Button_8 = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_8.setObjectName("Button_8")
    self.gridLayout.addWidget(self.Button_8, 1, 1, 1, 1)
    self.Button_4 = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_4.setObjectName("Button_4")
    self.gridLayout.addWidget(self.Button_4, 2, 0, 1, 1)
    self.Button_esc = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_esc.setObjectName("Button_esc")
    self.gridLayout.addWidget(self.Button_esc, 0, 0, 1, 1)
    self.Button_7 = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_7.setObjectName("Button_7")
    self.gridLayout.addWidget(self.Button_7, 1, 0, 1, 1)
    self.Button_1 = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_1.setObjectName("Button_1")
    self.gridLayout.addWidget(self.Button_1, 3, 0, 1, 1)
    self.Button_5 = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_5.setObjectName("Button_5")
    self.gridLayout.addWidget(self.Button_5, 2, 1, 1, 1)
    self.pushButton_17 = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.pushButton_17.setText("")
    self.pushButton_17.setObjectName("pushButton_17")
    self.gridLayout.addWidget(self.pushButton_17, 4, 0, 1, 1)
    self.Button_xiaoshu = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_xiaoshu.setObjectName("Button_xiaoshu")
    self.gridLayout.addWidget(self.Button_xiaoshu, 4, 1, 1, 1)
    self.Button_0 = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_0.setStyleSheet("")
    self.Button_0.setObjectName("Button_0")
    self.gridLayout.addWidget(self.Button_0, 4, 2, 1, 1)
    self.Button_dengyu = QtWidgets.QPushButton(self.gridLayoutWidget)
    self.Button_dengyu.setObjectName("Button_dengyu")
    self.gridLayout.addWidget(self.Button_dengyu, 4, 3, 1, 1)

    self.retranslateUi(Dialog)
    QtCore.QMetaObject.connectSlotsByName(Dialog)

  def retranslateUi(self, Dialog):
    _translate = QtCore.QCoreApplication.translate
    Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
    self.Edit_xianshi.setHtml(_translate("Dialog", "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">n"
"<html><head><meta name="qrichtext" content="1" /><style type="text/css">n"
"p, li { white-space: pre-wrap; }n"
"</style></head><body style=" font-family:'Aharoni'; font-size:16pt; font-weight:72; font-style:normal;">n"
"<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">0</p></body></html>"))
    self.Button_6.setText(_translate("Dialog", "6"))
    self.Button_2.setText(_translate("Dialog", "2"))
    self.Button_3.setText(_translate("Dialog", "3"))
    self.Button_fenzhi.setText(_translate("Dialog", "1/^"))
    self.Button_pingfang.setText(_translate("Dialog", "^2"))
    self.Button_add.setText(_translate("Dialog", " "))
    self.Button_jian.setText(_translate("Dialog", "-"))
    self.Button_9.setText(_translate("Dialog", "9"))
    self.Button_chu.setText(_translate("Dialog", "/"))
    self.Button_cheng.setText(_translate("Dialog", "*"))
    self.Button_8.setText(_translate("Dialog", "8"))
    self.Button_4.setText(_translate("Dialog", "4"))
    self.Button_esc.setText(_translate("Dialog", "esc"))
    self.Button_7.setText(_translate("Dialog", "7"))
    self.Button_1.setText(_translate("Dialog", "1"))
    self.Button_5.setText(_translate("Dialog", "5"))
    self.Button_xiaoshu.setText(_translate("Dialog", "."))
    self.Button_0.setText(_translate("Dialog", "0"))
    self.Button_dengyu.setText(_translate("Dialog", "="))


if __name__ == "__main__":
  import sys
  app = QtWidgets.QApplication(sys.argv)
  Dialog = QtWidgets.QDialog()
  ui = Ui_Dialog()
  ui.setupUi(Dialog)
  Dialog.show()
  sys.exit(app.exec_())

效果图:

9159.com 4

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持帮客之家。

PyQt5 Eric6 实现的一个计算器代码,pyqt5eric6 目前可以实现简单的计算。计算前请重置,设计的时候默认数字是0,学了半天就做出来...

目前可以实现简单的计算。计算前请重置,设计的时候默认数字是0,
学了半天就做出来个这么个结果,bug不少。 python3.5 PyQt5 Eric6 在windows7 32位系统可以完美运行 计算器,简单学了半天就画个图实现的存在bug,部分按钮还未实现,后续优化。

本文通过Python3 PyQt5实现自定义部件–Counters自定 窗口部件。这个窗口是3*3的网格。本文有两个例子如下:

代码结构如图:

/home/yrd/eric_workspace/chap11/counters.py。
/home/yrd/eric_workspace/chap11/counters_dnd.py

 9159.com 5

第二个例子在第一个例子的基础上实现能通过鼠标拖拽球到不同的网格中。

 1 jisuan.py
 2 import re
 3 #匹配整数或小数的乘除法,包括了开头存在减号的情况
 4 mul_div=re.compile("(-?d )(.d )?(*|/)(-?d )(.d )?")
 5 #匹配整数或小数的加减法,包括了开头存在减号的情况
 6 plus_minus = re.compile("(-?d )(.d )?(-| )(-?d )(.d )?")
 7 #匹配括号
 8 bracket=re.compile("([^()]*)")
 9 #匹配乘法的时候出现乘以负数的情况,包括了开头存在减号的情况
10 mul_minus_minus = re.compile("(-?d )(.d )?(*-)(d )(.d )?")
11 #匹配除法的时候出现乘以负数的情况,包括了开头存在减号的情况
12 div_minus_minus = re.compile("(-?d )(.d )?(/-)(d )(.d )?")
13 #定义一个两位数的加减乘除法的运算,匹配左边的右边的数字和左边的数字,然后进行计算
14 def touble_cale(str_expire):
15     if str_expire.count(" ") == 1:
16         right_num = float(str_expire[(str_expire.find(" ") 1):])
17         left_num = float(str_expire[:str_expire.find(" ")])
18         return str(right_num left_num)
19     elif str_expire[1:].count("-") == 1:
20         right_num = float(str_expire[:str_expire.find("-",1)])
21         left_num = float(str_expire[(str_expire.find("-", 1)   1):])
22         return str(right_num - left_num)
23     elif str_expire.count("*") == 1:
24         right_num = float(str_expire[:str_expire.find("*")])
25         left_num = float(str_expire[(str_expire.find("*") 1):])
26         return str(right_num * left_num)
27     elif str_expire.count("/") == 1:
28         right_num = float(str_expire[:str_expire.find("/")])
29         left_num = float(str_expire[(str_expire.find("/")   1):])
30         return str(right_num / left_num)
31 
32 
33 #定义一个方法用于判断是否存在乘以负数和除以负数的情况
34 def judge_mul_minus(str_expire):
35     #判断公式中乘以负数的部分
36     if len(re.findall("(*-)", str_expire)) != 0:
37         #调用上面的正则取得*-的公式
38         temp_mul_minus = mul_minus_minus.search(str_expire).group()
39         #将匹配的部分的*-换成*并将-放到前面
40         temp_mul_minus_2 = temp_mul_minus.replace(temp_mul_minus,"-"   temp_mul_minus.replace("*-","*"))
41         #经更改的的部分与原来的部分进行替换
42         str_expire=str_expire.replace(temp_mul_minus,temp_mul_minus_2)
43         return judge_mul_minus(str_expire)
44         #return str_expire
45     # 判断公式中除以负数的部分
46     elif len(re.findall(r"(/-)", str_expire)) != 0:
47         # 调用上面的正则取得/-的公式
48         temp_dev_minus = div_minus_minus.search(str_expire).group()
49         # 将匹配的部分的/-换成/并将-放到前面
50         temp_dev_minus_2 = temp_dev_minus.replace(temp_dev_minus,"-"   temp_dev_minus.replace("/-","/"))
51         # 经更改的的部分与原来的部分进行替换
52         str_expire = str_expire.replace(temp_dev_minus,temp_dev_minus_2)
53         return judge_mul_minus(str_expire)
54     #调用change_sign将公式中的  换成=  -换成-
55     return change_sign(str_expire)
56 
57 #定义一个方法取将--更改为   -改为-
58 def change_sign(str_expire):
59     if len(re.findall(r"( -)", str_expire)) != 0:
60         str_expire = str_expire.replace(" -", "-")
61         return change_sign(str_expire)
62     elif len(re.findall(r"(--)", str_expire)) != 0:
63         str_expire = str_expire.replace("--", " ")
64         return change_sign(str_expire)
65     return str_expire
66 
67 
68 #定义一个方法用于计算只有加减乘除的公式,优先处理乘法
69 def cale_mix(str_expire):
70     #如果公式中出现符号数字的情况即 5  -6 *8  /8的这种情况直接放回数字否则则先计算乘除在处理加减
71     while len(re.findall("[- */]",str_expire[1:])) != 0:
72         if len(re.findall("(*|/)",str_expire)) != 0:
73             str_expire = str_expire.replace(mul_div.search(str_expire).group(),touble_cale(mul_div.search(str_expire).group()))
74         elif len(re.findall("( |-)",str_expire)) !=0:
75             str_expire = str_expire.replace(plus_minus.search(str_expire).group(),touble_cale(plus_minus.search(str_expire).group()))
76     return str_expire
77 
78 #定义一个方法用于去括号,并调用上述的方法进行计算
79 def remove_bracket(str_expire):
80     #判断公式中是否有括号
81     if len(bracket.findall(str_expire)) == 0:
82         return cale_mix(judge_mul_minus(str_expire))
83     elif len(bracket.findall(str_expire))!=0:
84         while len(bracket.findall(str_expire)) !=0:
85             #print(bracket.search(str_expire).group())
86             #只有存在括号优先处理括号中的内容并对内容进行替换,直到没有括号位置
87             str_expire = str_expire.replace(bracket.search(str_expire).group(),cale_mix(judge_mul_minus(bracket.search(str_expire).group()[1:-1])))
88         str_expire = cale_mix(judge_mul_minus(str_expire))
89         return str_expire
90 if __name__ == "__main__":
91     while True:
92         user_input_expire = input("请输入你的公式:(不要带空格,q表示退出):")
93         print("%s=%s" %(user_input_expire,remove_bracket(user_input_expire)))
94         continue

untitled.py
# -*- coding: utf-8 -*-
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui, QtWidgets
from Ui_untitled import Ui_Dialog
from jisuan import remove_bracket
class Dialog(QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setupUi(self)
    @pyqtSlot()
    def on_Button_6_clicked(self):
        self.Edit_xianshi.insertPlainText('6')
    @pyqtSlot()
    def on_Button_2_clicked(self):
        self.Edit_xianshi.insertPlainText('2')
    @pyqtSlot()
    def on_Button_3_clicked(self):
        self.Edit_xianshi.insertPlainText('3')
    @pyqtSlot()
    def on_Button_pingfang_clicked(self):
        me=self.Edit_xianshi.toPlainText()
        m=int(me) *int(me)
        self.Edit_xianshi.clear()
        self.Edit_xianshi.append(str(m))
    @pyqtSlot()
    def on_Button_add_clicked(self):
        h=self.Edit_xianshi.toPlainText()
        self.Edit_xianshi.clear()
        self.Edit_xianshi.append(h ' ')
    @pyqtSlot()
    def on_Button_jian_clicked(self):
        h = self.Edit_xianshi.toPlainText()
        self.Edit_xianshi.clear()
        self.Edit_xianshi.append(h   '-')
    @pyqtSlot()
    def on_Button_9_clicked(self):
        self.Edit_xianshi.insertPlainText('9')
    @pyqtSlot()
    def on_Button_chu_clicked(self):
        h = self.Edit_xianshi.toPlainText()
        self.Edit_xianshi.clear()
        self.Edit_xianshi.append(h   '/')
    @pyqtSlot()
    def on_Button_cheng_clicked(self):
        h = self.Edit_xianshi.toPlainText()
        self.Edit_xianshi.clear()
        self.Edit_xianshi.append(h   '*')
    @pyqtSlot()
    def on_Button_8_clicked(self):
        self.Edit_xianshi.insertPlainText('8')
    @pyqtSlot()
    def on_Button_4_clicked(self):
        self.Edit_xianshi.insertPlainText('4')
    @pyqtSlot()
    def on_Button_esc_clicked(self):
        self.Edit_xianshi.clear()
    @pyqtSlot()
    def on_Button_7_clicked(self):
        self.Edit_xianshi.insertPlainText('7')
    @pyqtSlot()
    def on_Button_1_clicked(self):
        self.Edit_xianshi.insertPlainText('1')
    @pyqtSlot()
    def on_Button_5_clicked(self):
        self.Edit_xianshi.insertPlainText('5')
    @pyqtSlot()
    def on_Button_xiaoshu_clicked(self):
        self.Edit_xianshi.insertPlainText('.')
    @pyqtSlot()
    def on_Button_0_clicked(self):
        self.Edit_xianshi.insertPlainText('0')
    @pyqtSlot()
    def on_Button_dengyu_clicked(self):
        pe=self.Edit_xianshi.toPlainText()
        m=remove_bracket(pe)
        self.Edit_xianshi.clear()
        self.Edit_xianshi.append(str(m))

    def on_Button_fenzhi_clicked(self):
        pe = self.Edit_xianshi.toPlainText()
        if int(pe) ==0:
            QMessageBox.information(self,u'提示',u'零不能作为分母')
            Dialog()
        else:
            m=1/(int(pe))
            self.Edit_xianshi.clear()
            self.Edit_xianshi.append(str(m))
            Dialog()
if __name__ =="__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    app.processEvents()
    ui = Dialog()
    ui.show()

    sys.exit(app.exec_())

Ui_untitled.py
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'C:UsersAdministratorDesktoppyqt5untitled.ui'
#
# Created by: PyQt5 UI code generator 5.5
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(357, 320)
        Dialog.setStyleSheet("font: 75 16pt "Aharoni";n"
"background-color: rgb(206, 255, 251);")
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(201, 210, 301, 21))
        self.label.setText("")
        self.label.setObjectName("label")
        self.Edit_xianshi = QtWidgets.QTextEdit(Dialog)
        self.Edit_xianshi.setGeometry(QtCore.QRect(0, 0, 351, 41))
        self.Edit_xianshi.setStyleSheet("font: 75 16pt "Aharoni";")
        self.Edit_xianshi.setObjectName("Edit_xianshi")
        self.gridLayoutWidget = QtWidgets.QWidget(Dialog)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(0, 30, 351, 281))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setObjectName("gridLayout")
        self.Button_6 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_6.setObjectName("Button_6")
        self.gridLayout.addWidget(self.Button_6, 2, 2, 1, 1)
        self.Button_2 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_2.setObjectName("Button_2")
        self.gridLayout.addWidget(self.Button_2, 3, 1, 1, 1)
        self.Button_3 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_3.setObjectName("Button_3")
        self.gridLayout.addWidget(self.Button_3, 3, 2, 1, 1)
        self.Button_fenzhi = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_fenzhi.setObjectName("Button_fenzhi")
        self.gridLayout.addWidget(self.Button_fenzhi, 1, 3, 1, 1)
        self.Button_pingfang = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_pingfang.setObjectName("Button_pingfang")
        self.gridLayout.addWidget(self.Button_pingfang, 0, 3, 1, 1)
        self.Button_add = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_add.setObjectName("Button_add")
        self.gridLayout.addWidget(self.Button_add, 2, 3, 1, 1)
        self.Button_jian = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_jian.setObjectName("Button_jian")
        self.gridLayout.addWidget(self.Button_jian, 3, 3, 1, 1)
        self.Button_9 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_9.setObjectName("Button_9")
        self.gridLayout.addWidget(self.Button_9, 1, 2, 1, 1)
        self.Button_chu = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_chu.setObjectName("Button_chu")
        self.gridLayout.addWidget(self.Button_chu, 0, 2, 1, 1)
        self.Button_cheng = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_cheng.setObjectName("Button_cheng")
        self.gridLayout.addWidget(self.Button_cheng, 0, 1, 1, 1)
        self.Button_8 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_8.setObjectName("Button_8")
        self.gridLayout.addWidget(self.Button_8, 1, 1, 1, 1)
        self.Button_4 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_4.setObjectName("Button_4")
        self.gridLayout.addWidget(self.Button_4, 2, 0, 1, 1)
        self.Button_esc = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_esc.setObjectName("Button_esc")
        self.gridLayout.addWidget(self.Button_esc, 0, 0, 1, 1)
        self.Button_7 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_7.setObjectName("Button_7")
        self.gridLayout.addWidget(self.Button_7, 1, 0, 1, 1)
        self.Button_1 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_1.setObjectName("Button_1")
        self.gridLayout.addWidget(self.Button_1, 3, 0, 1, 1)
        self.Button_5 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_5.setObjectName("Button_5")
        self.gridLayout.addWidget(self.Button_5, 2, 1, 1, 1)
        self.pushButton_17 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.pushButton_17.setText("")
        self.pushButton_17.setObjectName("pushButton_17")
        self.gridLayout.addWidget(self.pushButton_17, 4, 0, 1, 1)
        self.Button_xiaoshu = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_xiaoshu.setObjectName("Button_xiaoshu")
        self.gridLayout.addWidget(self.Button_xiaoshu, 4, 1, 1, 1)
        self.Button_0 = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_0.setStyleSheet("")
        self.Button_0.setObjectName("Button_0")
        self.gridLayout.addWidget(self.Button_0, 4, 2, 1, 1)
        self.Button_dengyu = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.Button_dengyu.setObjectName("Button_dengyu")
        self.gridLayout.addWidget(self.Button_dengyu, 4, 3, 1, 1)

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.Edit_xianshi.setHtml(_translate("Dialog", "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">n"
"<html><head><meta name="qrichtext" content="1" /><style type="text/css">n"
"p, li { white-space: pre-wrap; }n"
"</style></head><body style=" font-family:'Aharoni'; font-size:16pt; font-weight:72; font-style:normal;">n"
"<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">0</p></body></html>"))
        self.Button_6.setText(_translate("Dialog", "6"))
        self.Button_2.setText(_translate("Dialog", "2"))
        self.Button_3.setText(_translate("Dialog", "3"))
        self.Button_fenzhi.setText(_translate("Dialog", "1/^"))
        self.Button_pingfang.setText(_translate("Dialog", "^2"))
        self.Button_add.setText(_translate("Dialog", " "))
        self.Button_jian.setText(_translate("Dialog", "-"))
        self.Button_9.setText(_translate("Dialog", "9"))
        self.Button_chu.setText(_translate("Dialog", "/"))
        self.Button_cheng.setText(_translate("Dialog", "*"))
        self.Button_8.setText(_translate("Dialog", "8"))
        self.Button_4.setText(_translate("Dialog", "4"))
        self.Button_esc.setText(_translate("Dialog", "esc"))
        self.Button_7.setText(_translate("Dialog", "7"))
        self.Button_1.setText(_translate("Dialog", "1"))
        self.Button_5.setText(_translate("Dialog", "5"))
        self.Button_xiaoshu.setText(_translate("Dialog", "."))
        self.Button_0.setText(_translate("Dialog", "0"))
        self.Button_dengyu.setText(_translate("Dialog", "="))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

/home/yrd/eric_workspace/chap11/counters.py

 

#!/usr/bin/env python3

from PyQt5.QtCore import (QRectF, QSize, Qt)
from PyQt5.QtWidgets import (QApplication, QSizePolicy,QWidget)
from PyQt5.QtGui import QPainter,QPen

BLANK, RED, YELLOW = range(3)


class CountersWidget(QWidget):

  def __init__(self, parent=None):
    super(CountersWidget, self).__init__(parent)
    self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding,
                    QSizePolicy.Expanding))
    self.grid = [[BLANK] * 3 for i in range(3)]
    self.selected = [0, 0]
    self.setMinimumSize(self.minimumSizeHint())


  def sizeHint(self):
    return QSize(200, 200)


  def minimumSizeHint(self):
    return QSize(100, 100)


  def mousePressEvent(self, event):
    xOffset = self.width() / 3
    yOffset = self.height() / 3
    if event.x() < xOffset:
      x = 0
    elif event.x() < 2 * xOffset:
      x = 1
    else:
      x = 2
    if event.y() < yOffset:
      y = 0
    elif event.y() < 2 * yOffset:
      y = 1
    else:
      y = 2
    cell = self.grid[x][y]
    if cell == BLANK:
      cell = RED
    elif cell == RED:
      cell = YELLOW
    else:
      cell = BLANK
    self.grid[x][y] = cell
    self.selected = [x, y]
    self.update()


  def keyPressEvent(self, event):
    if event.key() == Qt.Key_Left:
      self.selected[0] = (2 if self.selected[0] == 0
                else self.selected[0] - 1)
    elif event.key() == Qt.Key_Right:
      self.selected[0] = (0 if self.selected[0] == 2
                else self.selected[0]   1)
    elif event.key() == Qt.Key_Up:
      self.selected[1] = (2 if self.selected[1] == 0
                else self.selected[1] - 1)
    elif event.key() == Qt.Key_Down:
      self.selected[1] = (0 if self.selected[1] == 2
                else self.selected[1]   1)
    elif event.key() == Qt.Key_Space:
      x, y = self.selected
      cell = self.grid[x][y]
      if cell == BLANK:
        cell = RED
      elif cell == RED:
        cell = YELLOW
      else:
        cell = BLANK
      self.grid[x][y] = cell
    self.update()


  def paintEvent(self, event=None):
    painter = QPainter(self)
    painter.setRenderHint(QPainter.Antialiasing, True)
    xOffset = self.width() / 3
    yOffset = self.height() / 3
    for x in range(3):
      for y in range(3):
        cell = self.grid[x][y]
        rect = (QRectF(x * xOffset, y * yOffset,
            xOffset, yOffset).adjusted(0.5, 0.5, -0.5, -0.5))
        color = None
        if cell == RED:
          color = Qt.red
        elif cell == YELLOW:
          color = Qt.yellow
        if color is not None:
          painter.save()
          painter.setPen(Qt.black)
          painter.setBrush(color)
          painter.drawEllipse(rect.adjusted(2, 2, -2, -2))
          painter.restore()
        if [x, y] == self.selected:
          painter.setPen(QPen(Qt.blue, 3))
        else:
          painter.setPen(Qt.black)
        painter.drawRect(rect)


if __name__ == "__main__":
  import sys

  app = QApplication(sys.argv)
  form = CountersWidget()
  form.setWindowTitle("Counters")
  form.show()
  app.exec_()

 

/home/yrd/eric_workspace/chap11/counters_dnd.py

 

#!/usr/bin/env python3

from PyQt5.QtCore import (QRectF, QSize, Qt)
from PyQt5.QtWidgets import (QApplication, QSizePolicy,QWidget)
from PyQt5.QtGui import QPainter,QPen,QPixmap,QCursor
BLANK, RED, YELLOW = range(3)


class CountersWidget(QWidget):

  def __init__(self, parent=None):
    super(CountersWidget, self).__init__(parent)
    self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding,
                    QSizePolicy.Expanding))
    self.grid = [[BLANK] * 3 for i in range(3)]
    self.selected = [0, 0]
    self.setMinimumSize(self.minimumSizeHint())


  def sizeHint(self):
    return QSize(200, 200)


  def minimumSizeHint(self):
    return QSize(100, 100)


  def _xFromEventX(self, event):
    xOffset = self.width() / 3
    if event.x() < xOffset:
      x = 0
    elif event.x() < 2 * xOffset:
      x = 1
    else:
      x = 2
    return x


  def _yFromEventY(self, event):
    yOffset = self.width() / 3
    if event.y() < yOffset:
      y = 0
    elif event.y() < 2 * yOffset:
      y = 1
    else:
      y = 2
    return y


  def mouseDoubleClickEvent(self, event):
    x = self._xFromEventX(event)
    y = self._yFromEventY(event)
    cell = self.grid[x][y]
    if cell == BLANK:
      cell = RED
    elif cell == RED:
      cell = YELLOW
    else:
      cell = BLANK
    self.grid[x][y] = cell
    self.selected = [x, y]
    self.update()


  def keyPressEvent(self, event):
    if event.key() == Qt.Key_Left:
      self.selected[0] = (2 if self.selected[0] == 0
                else self.selected[0] - 1)
    elif event.key() == Qt.Key_Right:
      self.selected[0] = (0 if self.selected[0] == 2
                else self.selected[0]   1)
    elif event.key() == Qt.Key_Up:
      self.selected[1] = (2 if self.selected[1] == 0
                else self.selected[1] - 1)
    elif event.key() == Qt.Key_Down:
      self.selected[1] = (0 if self.selected[1] == 2
                else self.selected[1]   1)
    elif event.key() == Qt.Key_Space:
      x, y = self.selected
      cell = self.grid[x][y]
      if cell == BLANK:
        cell = RED
      elif cell == RED:
        cell = YELLOW
      else:
        cell = BLANK
      self.grid[x][y] = cell
    self.update()


  def paintEvent(self, event=None):
    painter = QPainter(self)
    painter.setRenderHint(QPainter.Antialiasing, True)
    xOffset = self.width() / 3
    yOffset = self.height() / 3
    for x in range(3):
      for y in range(3):
        cell = self.grid[x][y]
        rect = (QRectF(x * xOffset, y * yOffset,
            xOffset, yOffset).adjusted(0.5, 0.5, -0.5, -0.5))
        color = None
        if cell == RED:
          color = Qt.red
        elif cell == YELLOW:
          color = Qt.yellow
        if color is not None:
          painter.save()
          painter.setPen(Qt.black)
          painter.setBrush(color)
          painter.drawEllipse(rect.adjusted(2, 2, -2, -2))
          painter.restore()
        if [x, y] == self.selected:
          painter.setPen(QPen(Qt.blue, 3))
        else:
          painter.setPen(Qt.black)
        painter.drawRect(rect)


  def mousePressEvent(self, event):
    self.x = self._xFromEventX(event)
    self.y = self._yFromEventY(event)
    cell = self.grid[self.x][self.y]
    color = Qt.darkGray
    if cell == RED:
      color = Qt.red
    elif cell == YELLOW:
      color = Qt.yellow
    pixmap = QPixmap(12, 12)
    pixmap.fill(color)
    self.setCursor(QCursor(pixmap))


  def mouseReleaseEvent(self, event):
    x = self._xFromEventX(event)
    y = self._yFromEventY(event)
    if self.x != x or self.y != y:
      cell = self.grid[self.x][self.y]
      self.grid[self.x][self.y] = BLANK
      self.grid[x][y] = cell
      self.selected = [x, y]
      self.update()
    self.setCursor(Qt.ArrowCursor)


if __name__ == "__main__":
  import sys

  app = QApplication(sys.argv)
  form = CountersWidget()
  form.setWindowTitle("Counters")
  form.show()
  app.exec_()

 

运行结果:

 

9159.com 6

 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

效果图:

您可能感兴趣的文章:

  • python3 PyQt5实现支持多线程的页面索引器应用程序
  • python3 PyQt5 Qt Designer实现扩展对话框
  • python3 PyQt5 Qt Designer实现堆叠窗口部件
  • python3 PyQt5重新实现QT事件处理程序
  • python3 PyQt5重新实现自定义数据拖放处理
  • python3使用pyqt5制作一个超简单浏览器的实例
  • Python3使用PyQt5制作简单的画板/手写板实例
  • python3.5 PyQt5 Eric6 实现的一个计算器代码
  • python3 PyQt5实现使用剪贴板做复制与粘帖示例
  • python3 PyQt5图形项的自定义和交互 python3实现page Designer应用程序

9159.com 7

 github 传送门

本文由9159.com发布于编程,转载请注明出处:也希望大家多多支持脚本之家9159.com,目前可以实

关键词: 9159.com

上一篇:没有了
下一篇:没有了