在本文中,您将学习如何在 PyQt5 中使用文本框。 该小部件称为QLineEdit,并具有setText()来设置文本框值的方法,以及text()来获取值的方法。
我们可以使用resize(width, height)方法设置文本框的大小。 可以使用move(x, y)方法或使用网格布局来设置位置。
PyQt5 文本框
创建文本框非常简单:
self.textbox = QLineEdit(self)self.textbox.move(20, 20)self.textbox.resize(280,40)

PyQt5 文本框示例
下面的示例创建一个带有文本框的窗口。
import sysfrom PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QLineEdit, QMessageBoxfrom PyQt5.QtGui import QIconfrom PyQt5.QtCore import pyqtSlotclass App(QMainWindow):def __init__(self):super().__init__()self.title = 'PyQt5 textbox - pythonspot.com'self.left = 10self.top = 10self.width = 400self.height = 140self.initUI()def initUI(self):self.setWindowTitle(self.title)self.setGeometry(self.left, self.top, self.width, self.height)# Create textboxself.textbox = QLineEdit(self)self.textbox.move(20, 20)self.textbox.resize(280,40)# Create a button in the windowself.button = QPushButton('Show text', self)self.button.move(20,80)# connect button to function on_clickself.button.clicked.connect(self.on_click)self.show()@pyqtSlot()def on_click(self):textboxValue = self.textbox.text()QMessageBox.question(self, 'Message - pythonspot.com', "You typed: " + textboxValue, QMessageBox.Ok, QMessageBox.Ok)self.textbox.setText("")if __name__ == '__main__':app = QApplication(sys.argv)ex = App()sys.exit(app.exec_())
