PyQT5 輸入對話方塊
PyQt5 支援幾個輸入對話方塊,使用它們匯入 QInputDialog
。
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit
PyQt5 輸入對話方塊概述 :
![PyQt5 輸入對話方塊](/img/Tutorial/PyQt5/PyQt5 input dialog.png)
獲取整數
使用 QInputDialog.getInt()
獲取整數 :
def getInteger(self):
i, okPressed = QInputDialog.getInt(self, "Get integer","Percentage:", 28, 0, 100, 1)
if okPressed:
print(i)
按順序排列的引數:self,視窗標題,標籤(輸入框之前),預設值,最小值,最大值和步長。
獲取雙精度小數
使用 QInputDialog.getDouble()
獲取雙精度小數:
def getDouble(self):
d, okPressed = QInputDialog.getDouble(self, "Get double","Value:", 10.05, 0, 100, 10)
if okPressed:
print(d)
最後一個引數 10
是逗號後面的小數位數。
獲取元素/選擇
從下拉框中獲取元素:
def getChoice(self):
items = ("Red","Blue","Green")
item, okPressed = QInputDialog.getItem(self, "Get item","Color:", items, 0, False)
if okPressed and item:
print(item)
獲取字串
字串使用 QInputDialog.getText()
來獲取。
def getText(self):
text, okPressed = QInputDialog.getText(self, "Get text","Your name:", QLineEdit.Normal, "")
if okPressed and text != '':
print(text)
PyQt5 輸入對話方塊舉例
示例完整示例如下:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit
from PyQt5.QtGui import QIcon
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 input dialogs - tastones.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.getInteger()
self.getText()
self.getDouble()
self.getChoice()
self.show()
def getInteger(self):
i, okPressed = QInputDialog.getInt(self, "Get integer","Percentage:", 28, 0, 100, 1)
if okPressed:
print(i)
def getDouble(self):
d, okPressed = QInputDialog.getDouble(self, "Get double","Value:", 10.50, 0, 100, 10)
if okPressed:
print( d)
def getChoice(self):
items = ("Red","Blue","Green")
item, okPressed = QInputDialog.getItem(self, "Get item","Color:", items, 0, False)
if ok and item:
print(item)
def getText(self):
text, okPressed = QInputDialog.getText(self, "Get text","Your name:", QLineEdit.Normal, "")
if okPressed and text != '':
print(text)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())