You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 to window_main)
  • Inside the window, add a ScrolledWindow (to make the text area scrollable)
  • Inside the ScrolledWindow, add a TextView (set its ID to textview_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 like COM3; on Linux/macOS, they’re usually /dev/ttyUSB0 or /dev/ttyACM0.
  • Non-blocking Reads: Using GLib.timeout_add ensures 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:03:32