如何在QLCDNumber屏幕上显示多个数字?

时间:2020-06-26 10:36:49

标签: python python-3.x pyqt5 calculator qlcdnumber

我正在尝试使用Qt Designer创建简单的计算器,但是无法在QLCDNumber上显示多个数字。 例如,当我单击一次pushButton_1时,在屏幕上显示(1),没问题,但是第二次单击时却不显示(11)。当我使用LineEdit代替QLCDNumber时,可以使用“ 插入”方法(例如self.lineEdit.insert(value))并且可以显示多个数字。我们可以在QLCDNumber中使用类似的方法吗?

我们可以在QLCDNumber中使用类似的方法吗?

示例代码:

    self.pushButton_0.clicked.connect(lambda: self.display_screen("0"))
    self.pushButton_1.clicked.connect(lambda: self.display_screen("1"))
    self.pushButton_2.clicked.connect(lambda: self.display_screen("2"))
    self.pushButton_3.clicked.connect(lambda: self.display_screen("3"))
    self.pushButton_4.clicked.connect(lambda: self.display_screen("4"))
    self.pushButton_5.clicked.connect(lambda: self.display_screen("5"))
    self.pushButton_6.clicked.connect(lambda: self.display_screen("6"))
    self.pushButton_7.clicked.connect(lambda: self.display_screen("7"))
    self.pushButton_8.clicked.connect(lambda: self.display_screen("8"))
    self.pushButton_9.clicked.connect(lambda: self.display_screen("9"))
    self.pushButton_dot.clicked.connect(lambda: self.display_screen("."))
    self.pushButton_00.clicked.connect(lambda: self.display_screen("00"))
    self.pushButton_add.clicked.connect(lambda: self.display_screen("+"))
    self.pushButton_minus.clicked.connect(lambda: self.display_screen("-"))
    self.pushButton_multiply.clicked.connect(lambda: self.display_screen("*"))
    self.pushButton_divide.clicked.connect(lambda: self.display_screen("/"))
    #self.pushButton_equal.clicked.connect(lambda: self.display_screen("="))
    self.pushButton_equal.clicked.connect(lambda:self.calculation)

    self.pushButton_sil.clicked.connect(self.lineEdit.backspace)
    self.pushButton_clear.clicked.connect(self.lineEdit.clear)

def display_screen(self,value):
    self.lineEdit.insert(value)

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案是创建一个变量,该变量通过执行所需的操作来构建字符串:

from PyQt5 import QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.text = ""

        self.lcd_number = QtWidgets.QLCDNumber()

        button_1 = QtWidgets.QPushButton("1", clicked=lambda: self._handle_clicked("1"))
        button_2 = QtWidgets.QPushButton("2", clicked=lambda: self._handle_clicked("2"))
        button_3 = QtWidgets.QPushButton("3", clicked=lambda: self._handle_clicked("3"))
        button_4 = QtWidgets.QPushButton("4", clicked=lambda: self._handle_clicked("4"))

        lay = QtWidgets.QGridLayout(self)
        lay.addWidget(button_1, 0, 0)
        lay.addWidget(button_2, 0, 1)
        lay.addWidget(button_3, 0, 2)
        lay.addWidget(button_4, 0, 3)
        lay.addWidget(self.lcd_number)

    def _handle_clicked(self, s):
        self.text += s
        self.lcd_number.display(self.text)


if __name__ == "__main__":

    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())