能用pyqt5写一个简单的示范吗
时间: 2024-05-24 12:04:42 浏览: 9
当然可以,请参考下方代码示例:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton
class ChatBot(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 设置窗口大小和标题
self.setGeometry(100, 100, 400, 300)
self.setWindowTitle('ChatBot')
# 创建对话内容显示框
self.conversation = QLabel('Welcome to ChatBot!', self)
self.conversation.setWordWrap(True)
self.conversation.setStyleSheet('font-size: 14pt; font-family: Microsoft YaHei;')
self.conversation.setAlignment(4)
# 创建输入框和发送按钮
self.input_text = QLineEdit()
self.send_button = QPushButton('Send')
self.send_button.setStyleSheet('background-color: #4CAF50; color: white; font-size: 14pt; font-family: Microsoft YaHei;')
# 将输入框和发送按钮放在水平布局中
hbox = QHBoxLayout()
hbox.addWidget(self.input_text)
hbox.addWidget(self.send_button)
# 将对话内容显示框和水平布局放在垂直布局中
vbox = QVBoxLayout()
vbox.addWidget(self.conversation)
vbox.addLayout(hbox)
# 将整个窗口设置为垂直布局
self.setLayout(vbox)
# 绑定发送按钮的点击事件
self.send_button.clicked.connect(self.send_message)
# 显示窗口
self.show()
def send_message(self):
# 获取用户输入的内容
message = self.input_text.text()
# 将用户输入的内容显示在对话内容显示框中
self.conversation.setText(self.conversation.text() + '\n' + 'User: ' + message)
# TODO: 调用 AI 模型,生成机器人的回复
reply = 'I am a simple ChatBot.'
# 将机器人的回复显示在对话内容显示框中
self.conversation.setText(self.conversation.text() + '\n' + 'ChatBot: ' + reply)
# 清空输入框
self.input_text.clear()
if __name__ == '__main__':
app = QApplication(sys.argv)
chatbot = ChatBot()
sys.exit(app.exec_())
```
这是一个简单的聊天机器人界面,包含了一个对话内容显示框、一个输入框和一个发送按钮。用户输入信息后,点击发送按钮,程序会调用 AI 模型,生成机器人的回复,并将对话内容显示在对话内容显示框中。