python 获取 QLineEdit 里输入的文本
时间: 2024-04-27 22:20:08 浏览: 9
在 Python 中,你可以使用 `QLineEdit` 的 `text()` 方法来获取文本框中输入的文本。具体用法如下:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QPushButton, QVBoxLayout
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.line_edit = QLineEdit(self)
self.button = QPushButton('获取文本', self)
self.button.clicked.connect(self.get_text)
vbox = QVBoxLayout()
vbox.addWidget(self.line_edit)
vbox.addWidget(self.button)
self.setLayout(vbox)
self.show()
def get_text(self):
text = self.line_edit.text()
print(text)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyWidget()
sys.exit(app.exec_())
```
在上面的代码中,我们创建了一个 `QLineEdit` 对象和一个按钮,点击按钮时会调用 `get_text()` 方法,该方法会获取文本框中的文本并打印出来。`text()` 方法返回的是一个字符串,即文本框中输入的文本。