I want to create a user interface with tkinter and it includes reading serial ports. I use code like this
from tkinter.ttk import Combobox
import serial
import sys
import serial.tools.list_ports
from tkinter.messagebox import showinfo
from tkinter import *
window=Tk()
window.title("test cell")
ports=list(serial.tools.list_ports.comports())
selected=StringVar(window)
m_select=Combobox(window,textvariable=selected)
m_select['values']=ports
m_select['state']='readonly'
m_select.place(x=0,y=0)
window.mainloop()
in this case I can read all connected devices but if I connect or disconnect a new device I can not see it and I have to close the file and run it again. is there any way that I could refresh it automatically and do not need to close it??
CodePudding user response:
See the below example to update the list inside the combobox when the down arrow is clicked.
I've tested this with a dummy function that returns a random number of com ports but this should work the same with the serial.tools.comports
function.
(You'll need to comment back in lines that you require, I don't have serial on this PC)
from tkinter.ttk import Combobox
#import serial
import sys
#import serial.tools.list_ports
from tkinter.messagebox import showinfo
from tkinter import *
def comports():
"""Dummy function, remove me for the real thing"""
import random
ports = [f"COM{i}" for i in range(random.randint(1,10))]
return ports
def updateComPortList():
#ports=list(serial.tools.list_ports.comports())
ports = comports()
m_select['values']=ports
window=Tk()
window.title("test cell")
selected=StringVar(window)
m_select=Combobox(window,textvariable=selected,postcommand = updateComPortList)
m_select['state']='readonly'
m_select.place(x=0,y=0)
window.mainloop()