原文: https://pythonspot.com/pyqt5-input-dialog/

PyQt5 支持多个输入对话框,使用它们可以导入QInputDialog

  1. from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit

PyQt5 输入对话框概述:

PyQT5 输入对话框 - 图1

获取整数

使用QInputDialog.getInt()获取整数:

  1. def getInteger(self):
  2. i, okPressed = QInputDialog.getInt(self, "Get integer","Percentage:", 28, 0, 100, 1)
  3. if okPressed:
  4. print(i)

参数顺序如下:自身,窗口标题,标签(在输入框之前),默认值,最小,最大和步长。

获得浮点

通过QInputDialog.getDouble()获得双倍:

  1. def getDouble(self):
  2. d, okPressed = QInputDialog.getDouble(self, "Get double","Value:", 10.05, 0, 100, 10)
  3. if okPressed:
  4. print(d)

最后一个参数(10)是逗号后面的小数位数。

获取/选择项目

从下拉框中获取一个项目:

  1. def getChoice(self):
  2. items = ("Red","Blue","Green")
  3. item, okPressed = QInputDialog.getItem(self, "Get item","Color:", items, 0, False)
  4. if okPressed and item:
  5. print(item)

获取字符串

使用QInputDialog.getText()获取字符串

  1. def getText(self):
  2. text, okPressed = QInputDialog.getText(self, "Get text","Your name:", QLineEdit.Normal, "")
  3. if okPressed and text != '':
  4. print(text)

所有 PyQt5 输入对话框的示例

下面的完整示例:

  1. import sys
  2. from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit
  3. from PyQt5.QtGui import QIcon
  4. class App(QWidget):
  5. def __init__(self):
  6. super().__init__()
  7. self.title = 'PyQt5 input dialogs - pythonspot.com'
  8. self.left = 10
  9. self.top = 10
  10. self.width = 640
  11. self.height = 480
  12. self.initUI()
  13. def initUI(self):
  14. self.setWindowTitle(self.title)
  15. self.setGeometry(self.left, self.top, self.width, self.height)
  16. self.getInteger()
  17. self.getText()
  18. self.getDouble()
  19. self.getChoice()
  20. self.show()
  21. def getInteger(self):
  22. i, okPressed = QInputDialog.getInt(self, "Get integer","Percentage:", 28, 0, 100, 1)
  23. if okPressed:
  24. print(i)
  25. def getDouble(self):
  26. d, okPressed = QInputDialog.getDouble(self, "Get double","Value:", 10.50, 0, 100, 10)
  27. if okPressed:
  28. print( d)
  29. def getChoice(self):
  30. items = ("Red","Blue","Green")
  31. item, okPressed = QInputDialog.getItem(self, "Get item","Color:", items, 0, False)
  32. if ok and item:
  33. print(item)
  34. def getText(self):
  35. text, okPressed = QInputDialog.getText(self, "Get text","Your name:", QLineEdit.Normal, "")
  36. if okPressed and text != '':
  37. print(text)
  38. if __name__ == '__main__':
  39. app = QApplication(sys.argv)
  40. ex = App()
  41. sys.exit(app.exec_())

下载 PyQT5 示例