如何在python中输入超过特定数值的数字

问题描述

我想在 Python 中限制 PyQt5 QLineEdit Gui 中的数字输入值。

说明照片如下。

enter image description here

风向为 0 到 359 度。

所以,可以输入的值是从 0 到 359。

我制作的代码如下。

class Ship_Use_Tug_Input_Program(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        wd = QLabel('Wind Direction',self)
        wd.move(40,300)
        wd_ent = QLineEdit(self)
        wd_ent.move(180,295)
        wd_ent.resize(80,25)
        wd_font = wd.font()
        wd_font.setBold(False)
        wd.setFont(wd_font)
        QToolTip.setFont(QFont('Times New Roman',8))
        wd.setToolTip('Please type 000 form\nExample)090 degree direction->"Type 090"')

        file = pathlib.Path('C:/Users/woody/OneDrive/Desktop/Python Workspace/Ship_Use_Tug_Input_Program.xlsx')
        if file.exists():
            pass
        else:
            file=Workbook()
            sheet = file.active
            file.save('C:/Users/woody/OneDrive/바탕 화면/Python Workspace/Ship_Use_Tug_Input_Program.xlsx')

        def save_to_excel(self):
            file = openpyxl.load_workbook('C:/Users/woody/OneDrive/바탕 화면/Python Workspace/Ship_Use_Tug_Input_Program.xlsx')
            sheet = file.active

            file.save('C:/Users/woody/OneDrive/바탕 화면/Python Workspace/Ship_Use_Tug_Input_Program.xlsx')

        btn_save = QPushButton('Save',self)
        btn_save.clicked.connect(save_to_excel)
        btn_save.move(380,520)

        self.setwindowTitle('Ship use tug input program')
        self.setFixedSize(945,570)
        self.show()

if __name__ == '__main__':
  app = QApplication(sys.argv)
  ex = Ship_Use_Tug_Input_Program()
  sys.exit(app.exec_())

解决方法

在这些情况下,最好使用允许用户输入特定范围内的整数值的 QSpinbox:

wd_ent = QSpinBox(minimum=0,maximum=359)

另一种选择是使用 QIntValidator。

注意: Qt 提供了不同类型的小部件来获取不同类型的信息(整数、浮点数、字符串、日期、时间等),因此建议您查看选项,以便您可以以简单的方式处理数据。