Ubuntu 16.04下Python+PyGTK(Glade)串口数据转TextView显示示例需求
Python + PyGTK (Glade) 串口数据显示示例
Got it! I’ve been there too—combining serial port reads with GTK can be tricky because you don’t want to block the UI thread. Let’s walk through a complete working example step by step.
1. 先安装依赖
First, make sure you have the required packages installed:
pip install pyserial pygobject
You’ll also need Glade to design your UI (most Linux distros have it in their software repos, or you can download it for Windows/macOS directly).
2. 设计Glade界面
Open Glade and build a simple UI with these elements:
- A top-level
Window(set its ID towindow_main) - Inside the window, add a
ScrolledWindow(to make the text area scrollable) - Inside the ScrolledWindow, add a
TextView(set its ID totextview_serial)
Save this UI file as serial_ui.glade in the same folder as your Python script.
3. 完整Python代码
This example uses non-blocking serial reads with GLib timers to keep the UI responsive—no frozen windows!
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GLib import serial class SerialMonitor: def __init__(self): # Load the Glade UI file self.builder = Gtk.Builder() self.builder.add_from_file("serial_ui.glade") # Get references to UI widgets self.window = self.builder.get_object("window_main") self.textview = self.builder.get_object("textview_serial") self.textbuffer = self.textview.get_buffer() # Configure serial port (adjust these to match your device!) self.ser = None try: self.ser = serial.Serial( port='/dev/ttyUSB0', # Windows users: use something like 'COM3' baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1 ) print("Serial port connected successfully!") except serial.SerialException as e: print(f"Failed to connect to serial port: {e}") # Set up window close handler self.window.connect("destroy", self.on_window_close) # Start a timer to read serial data every 100ms (non-blocking) if self.ser: GLib.timeout_add(100, self.read_and_update_serial) # Show the main window self.window.show_all() def read_and_update_serial(self): """Read serial data and update the TextView (runs in UI thread)""" if not self.ser or not self.ser.is_open: return False # Stop the timer if serial is closed # Check if there's data waiting to be read if self.ser.in_waiting > 0: try: # Read a line of text (adjust this if your data uses a different format) data = self.ser.readline().decode('utf-8').strip() if data: # Insert the data at the end of the TextView end_iter = self.textbuffer.get_end_iter() self.textbuffer.insert(end_iter, f"{data}\n") # Auto-scroll to the bottom so we see the latest data self.textview.scroll_to_iter(end_iter, 0.0, False, 0.0, 1.0) except UnicodeDecodeError: # Handle binary data or encoding issues end_iter = self.textbuffer.get_end_iter() self.textbuffer.insert(end_iter, "[Binary data (could not decode)]\n") return True # Return True to keep the timer running def on_window_close(self, widget): """Clean up serial port when window closes""" if self.ser and self.ser.is_open: self.ser.close() print("Serial port closed.") Gtk.main_quit() if __name__ == "__main__": app = SerialMonitor() Gtk.main()
关键注意事项
- Serial Port Settings: Double-check the
port,baudrate, and other parameters match your device’s configuration. For Windows, ports are named likeCOM3; on Linux/macOS, they’re usually/dev/ttyUSB0or/dev/ttyACM0. - Non-blocking Reads: Using
GLib.timeout_addensures we never block the UI thread—this is the most important part of keeping your app responsive. - Data Format: If you’re dealing with binary data instead of plain text, replace the decode step with something like
data = self.ser.read(10).hex()to display hex values. - Error Handling: The example includes basic error handling for serial connection issues and encoding errors—you can expand this based on your specific use case.
内容的提问来源于stack exchange,提问作者uyghur nature
相关产品推荐
相关产品推荐

