user119o
user119o

Reputation: 387

Get available all COM port to tkinter combo box in Python

I have a tkinter GUI with a Combo box.

I want to get all available COM ports to combo box at starting GUI and I need to perform a function while changing combo box value.

I have pyserial and I'm using Python 2.7.

How can I do this?

UPDATE

This is the function for get COM ports..I want to bind this for my GUI.And I need a combo box changing event.

import sys
import glob
import serial


def serial_ports():


    ports = ['COM%s' % (i + 1) for i in range(256)]

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result


if __name__ == '__main__':
    print(serial_ports())

I have added this configuration for get the ports in to combo box.

self.comboComNum.configure(values=serial_ports())

QUESTION

How can I implement a more accurate and faster function for get COM ports?

How can I get combo box changing event?

Upvotes: 1

Views: 9383

Answers (2)

Rafalenfs
Rafalenfs

Reputation: 37

#Muestra los Puertos COM en Python
import serial.tools.list_ports
# Llamamos a la libreria que nos ayudara a buscar
# los puertos habilidatos.


find_com = serial.tools.list_ports

COM = find_com.comports()

#Nos devuelve una lista
# EL primer parametro es el puerto.
print(COM[0]) # Nombre completo del puerto.
print(COM[0][0]) # Solo puerto COM#

Upvotes: 0

furas
furas

Reputation: 142631

There is serial.tools.list_ports and maybe it will work faster (I don't use Windows so I can test it)

import serial.tools.list_ports

print serial.tools.list_ports.comports()

You got in comment link to example combobox-get-selection

Here shorter version

import tkinter as tk
import tkinter.ttk as ttk
import serial.tools.list_ports

# --- functions ---

def serial_ports():    
    return serial.tools.list_ports.comports()

def on_select(event=None):

    # get selection from event    
    print("event.widget:", event.widget.get())

    # or get selection directly from combobox
    print("comboboxes: ", cb.get())

# --- main ---

root = tk.Tk()

cb = ttk.Combobox(root, values=serial_ports())
cb.pack()

# assign function to combobox
cb.bind('<<ComboboxSelected>>', on_select)

root.mainloop()

Upvotes: 4

Related Questions