Learning Python
1. Pre-learning Highlights
Design a dialog box between two good friends using Python’s PyQt module, where messages sent by both parties can be displayed in each other’s area. The previous PyQt implementation for “Learning Management” used a database for storage. This time, we will use a file to record the dialogue information.
As for whether to use a database or a file in actual projects, generally speaking, files are lightweight, do not involve third-party software installation, and are easy to use, but subsequent processing is not as intuitive as with a database. In formal projects, backend storage typically uses a database, which supports SQL language, making querying and modifying easier.
2. Implementation of Chat Dialog Using Python’s PyQt5
2.1 Program Planning
The program code should include a complete interface layout, message sending and receiving logic, and file recording functionality, with clear comments for direct execution. Functionality description:
1. Divided into two dialogue areas for “Xiao Ming” and “Xiao Li”, where messages sent by both parties will be displayed in each other’s chat window in real-time;
2. Supports multi-line text input and sending via Enter (can also click the send button);
3. Each time a message is sent, automatically append “Sender + Time + Content” to the chat_record.txt file;
4. The interface distinguishes the message sender (different colors/alignment) to enhance readability.
2.2 Program Example:
|
import sys import datetime from PyQt5.QtWidgets import ( QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QTextEdit, QPushButton, QLabel, QScrollArea ) from PyQt5.QtCore import Qt, QDateTime from PyQt5.QtGui import QTextCharFormat, QColor, QFont
class ChatWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle(“Xiao Ming – Xiao Li Two-way Dialog Box”) self.setMinimumSize(800, 600)
# Initialize file (create if it does not exist) self.chat_file = “chat_record.txt” with open(self.chat_file, “a”, encoding=”utf-8″) as f: f.write(f”\n===== Dialogue Start: {QDateTime.currentDateTime().toString(‘yyyy-MM-dd HH:mm:ss’)} =====\n”)
# Create central component central_widget = QWidget() self.setCentralWidget(central_widget)
# Overall layout: left and right columns (Xiao Ming + Xiao Li) main_layout = QHBoxLayout(central_widget) main_layout.setSpacing(20) main_layout.setContentsMargins(20, 20, 20, 20)
# 1. Create Xiao Ming’s chat area (saved as an instance property to avoid overwriting) self.user_panel = self._create_chat_panel(“Xiao Ming”) # 2. Create Xiao Li’s chat area (saved as an instance property) self.client_panel = self._create_chat_panel(“Xiao Li”)
main_layout.addWidget(self.user_panel, stretch=1) main_layout.addWidget(self.client_panel, stretch=1)
def _create_chat_panel(self, panel_name): “””Create a single chat panel (title + chat display area + input area + send button)””” panel = QWidget() layout = QVBoxLayout(panel)
# Panel title title_label = QLabel(panel_name) title_label.setAlignment(Qt.AlignCenter) title_label.setFont(QFont(“Microsoft YaHei”, 12, QFont.Bold)) layout.addWidget(title_label)
# Chat display area (read-only, with scroll) display = QTextEdit() display.setReadOnly(True) display.setFont(QFont(“Microsoft YaHei”, 10)) display.setStyleSheet(“border: 1px solid #ccc; padding: 10px;”) layout.addWidget(display, stretch=5)
# Input area + send button layout input_layout = QHBoxLayout() msg_input = QTextEdit() msg_input.setPlaceholderText(“Enter message (send with Enter)”) msg_input.setFont(QFont(“Microsoft YaHei”, 10)) msg_input.setMaximumHeight(100) input_layout.addWidget(msg_input, stretch=4)
send_btn = QPushButton(“Send”) send_btn.setStyleSheet(“background-color: #409EFF; color: white; border: none; padding: 8px;”) # Bind send button: pass the current panel’s input box, display area, and name send_btn.clicked.connect(lambda: self._send_message(panel_name, msg_input, display)) input_layout.addWidget(send_btn, stretch=1)
layout.addLayout(input_layout, stretch=1)
# Bind Enter to send (distinguish between normal Enter and Shift+Enter) # Bind Enter event separately for each input box, passing panel information def custom_key_press(event, input_box=msg_input, name=panel_name): self._handle_enter(event, input_box, name) msg_input.keyPressEvent = custom_key_press
# Bind properties to the panel (for easy access later) panel.display = display panel.input = msg_input panel.name = panel_name
return panel
def _handle_enter(self, event, input_box, panel_name): “””Handle Enter event: normal Enter sends, Shift+Enter creates a new line””” if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter: if event.modifiers() & Qt.ShiftModifier: # Shift+Enter: normal new line QTextEdit.keyPressEvent(input_box, event) else: # Normal Enter: send message (pass current input box) self._send_message(panel_name, input_box, None) else: # Other keys are processed normally QTextEdit.keyPressEvent(input_box, event)
def _send_message(self, sender_name, input_box, sender_display): “””Core logic for sending messages: only display in the other party’s window + record to file””” # Get the input message and trim whitespace msg_content = input_box.toPlainText().strip() if not msg_content: return # Do not send empty messages
# Determine the receiving panel if sender_name == “Xiao Ming”: receiver_panel = self.client_panel # User sends → Xiao Li receives sender_panel = self.user_panel # Sender’s own panel (for clearing input) else: receiver_panel = self.user_panel # Xiao Li sends → Xiao Ming receives sender_panel = self.client_panel # Sender’s own panel
# Get the current time current_time = QDateTime.currentDateTime().toString(“HH:mm:ss”) # 1. Format message (distinguish sender, different colors) sender_format = QTextCharFormat() sender_format.setForeground(QColor(“#409EFF”) if sender_name == “Xiao Ming” else QColor(“#67C23A”)) sender_format.setFontWeight(QFont.Bold)
# ✅ Only display in the receiver’s window (left-aligned) receiver_panel.display.append(f”\n【{sender_name} {current_time}】”) receiver_panel.display.setTextCursor(receiver_panel.display.textCursor()) receiver_panel.display.setCurrentCharFormat(sender_format) receiver_panel.display.insertPlainText(msg_content) receiver_panel.display.setAlignment(Qt.AlignLeft)
# 2. Record to file with open(self.chat_file, “a”, encoding=”utf-8″) as f: f.write(f”[{current_time}] {sender_name}:{msg_content}\n”)
# 3. Clear the sender’s input box input_box.clear()
# 4. Scroll the receiver’s window to the latest message receiver_panel.display.verticalScrollBar().setValue( receiver_panel.display.verticalScrollBar().maximum() )
if __name__ == “__main__”: app = QApplication(sys.argv) window = ChatWindow() window.show() sys.exit(app.exec_()) |
After the program is executed, the result is as follows:
![Learning Python [40]: Clever Use of Python's PyQt5 and File for Chat Dialog](https://boardor.com/wp-content/uploads/2026/01/58ee2a6f-72da-4f66-8dea-0d5fffc6f90d.png)
The dialogue information of both parties is saved in the file “chat_record.txt”. We check the file and it shows as follows:
![Learning Python [40]: Clever Use of Python's PyQt5 and File for Chat Dialog](https://boardor.com/wp-content/uploads/2026/01/e7d92ce3-1dab-48e9-8227-b4a29e9c70c2.png)
3. Summary
Today we learned how to design a dialog box function using Python’s PyQt module, allowing both parties to send messages to each other, with all information recorded in a file. This type of application makes us love Python even more and makes learning more enjoyable.
Let’s maintain our enthusiasm for learning and practice more. See you next time!
![Learning Python [40]: Clever Use of Python's PyQt5 and File for Chat Dialog](https://boardor.com/wp-content/uploads/2026/01/e456a6e9-6a3d-4c52-9691-e33d52e8c151.png)
#python