使用 PyQt 在 Python 中输入带有验证的弹出框

Input pup up box with validation in Python using PyQt

我有一个 python 脚本,它将订单号作为输入,输出将是商品成本、税金和总计。也是物品运送的地址。 在这个程序中,我有以下代码来获取输入

Oname = '1'  #something that doesn't validate
while True:
    Oname = input("Please enter the Order number: ").upper() #ask for order number
    if not re.match(r"\b[A-Z]{2}[-][0-9]{6}\b", Oname): #check if the Order number is in the right format
        print ("Error! Please enter Order in format 'RS-XXXXXX'") #if the Order number is not in the right format, keep asking
    else:
        break

一切正常。但是,我想用弹出式输入框(使用 pyQT4)而不是命令行来做到这一点(我与其他人分享这个,他们更喜欢弹出式框而不是命令行)。 此外,我需要在弹出 window 上有一个取消按钮,如果用户单击它(用户可能改变了主意并且不想 运行 该程序),python脚本应该停止。

以上两项是绝对必要的。 愿望清单上的另一项是,在名为 "is this a gift item" 的输入字段旁边应该有一个复选框。如果用户选中此框,则只应打印 "the item has been shipped to xxxxx address" 消息。计算价格的代码部分不必是 运行.

抱歉,我有 PyQt5。 试一试:

import sys 
#from PyQt4.QtCore    import *
#from PyQt4.QtGui     import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore    import *
from PyQt5.QtGui     import *

class Demo(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)

        self.label = QLabel("Please enter Order in format `RS-XXXXXX`:", alignment=Qt.AlignCenter)
        self.chBox = QCheckBox("<-is this a gift item")

        self.lineEdit= QLineEdit()

        # a cancel button
        self.lineEdit.setClearButtonEnabled(True)

        self.lineEdit.setToolTip("press RETURN to check")
        self.lineEdit.setStyleSheet(""" QLineEdit {border: None;
                                                   font-size: 14px;} """)
        # lineEdit with validation                                              
        self.lineEdit.setInputMask('AA-999999')    
        self.lineEdit.returnPressed.connect(lambda : self.findText(self.lineEdit.text()))

        self.textBrowser = QTextBrowser()
        self.button = QPushButton("click me to check")
        self.button.clicked.connect(lambda : self.findText(self.lineEdit.text()))

        self.grid = QGridLayout(centralWidget)
        self.grid.addWidget(self.label,       0, 0, 1, 2)  
        self.grid.addWidget(self.chBox,       1, 0)
        self.grid.addWidget(self.lineEdit,    1, 1)
        self.grid.addWidget(self.textBrowser, 2, 0, 1, 2)   
        self.grid.addWidget(self.button,      3, 0, 1, 2)

    def findText(self, text=None):
        if self.lineEdit.hasAcceptableInput():
            self.textBrowser.append(text)      
            if self.chBox.isChecked():  
                self.textBrowser.insertPlainText("; chBox -> True. Is this a gift item.")        


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mw = Demo()
    mw.show()
    sys.exit(app.exec_())