219.md 1.6 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4
# PyQt4 文本框

> 原文: [https://pythonspot.com/qt4-textbox-example/](https://pythonspot.com/qt4-textbox-example/)

W
wizardforcel 已提交
5 6
![pyqt textbox](img/b2c2549d84491412df87f80cf61fbbdc.jpg)

W
wizardforcel 已提交
7
PyQt4 文本框示例
W
wizardforcel 已提交
8 9 10 11 12 13 14

在本文中,您将学习如何使用 [PyQt4](https://pythonspot.com/pyqt4/) 与文本框进行交互。

如果要在文本框(QLineEdit)中显示文本,则可以使用 setText()方法。

## PyQt4 QLineEdit

W
wizardforcel 已提交
15
如果按下按钮,下面的文本框示例将更改文本。
W
wizardforcel 已提交
16

W
wizardforcel 已提交
17
```py
W
wizardforcel 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
import sys
from PyQt4.QtCore import pyqtSlot
from PyQt4.QtGui import *

# create our window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle('Textbox example @pythonspot.com')

# Create textbox
textbox = QLineEdit(w)
textbox.move(20, 20)
textbox.resize(280,40)

# Set window size.
w.resize(320, 150)

# Create a button in the window
button = QPushButton('Click me', w)
button.move(20,80)

# Create the actions
@pyqtSlot()
def on_click():
    textbox.setText("Button clicked.")

# connect the signals to the slots
button.clicked.connect(on_click)

# Show the window and run the app
w.show()
app.exec_()

```

使用以下行创建文本字段:

W
wizardforcel 已提交
55
```py
W
wizardforcel 已提交
56 57 58 59 60 61 62 63
textbox = QLineEdit(w)
textbox.move(20, 20)
textbox.resize(280,40)

```

该按钮(来自屏幕截图)由以下部分制成:

W
wizardforcel 已提交
64
```py
W
wizardforcel 已提交
65 66 67 68 69 70
button = QPushButton('Click me', w)

```

我们通过以下方式将按钮连接到 on_click 函数:

W
wizardforcel 已提交
71
```py
W
wizardforcel 已提交
72 73 74 75 76 77 78 79
# connect the signals to the slots
button.clicked.connect(on_click)

```

此函数使用 setText()设置文本框。

[下载 PyQT 代码(批量收集)](https://pythonspot.com/python-qt-examples/)