Question

I am working on a Python program that logs data from serial ports to .txt files. The program uses Tkinter's OptionMenu to ask the user what serial port to use. The list of ports is made as follows:

def serial_ports():
    for port in list_ports.comports():
        yield port
OPTIONS = list(serial_ports())

Then the program makes the OptionMenu (window name = 'win', frame = 'c'):

var = StringVar(win)
var.set(OPTIONS[0]) # initial value
    for item in OPTIONS:
        print item #statement here is temporary to prevent the prog from giving error while testing
w =  apply(OptionMenu, (c, var, item))
w.pack(side=RIGHT)

I get the items to print subsequently but I can't find a way to get them in the OptionMenu. Code like:

for n in OPTIONS:
    #tried different things here: count, n = item, et whatever crazy stuff one tries.
w =  apply(OptionMenu, (c, var, OPTIONS[n]))

did not solve the problem.

The idea in the end is that the chosen of the OptionMenu returns the name of the serial port , in preferably a string (not an index). Wich will be inserted in:

ser0 = serial.Serial(port = '[HERE!!!]', baudrate = 9600, timeout = 0.5)

ps. For now the program is written for Mac OS X with Python 2.7.1.

Was it helpful?

Solution

To make an OptionMenu with all the options in the list OPTIONS, use:

w =  OptionMenu(c, var, *OPTIONS)

For example,

import Tkinter as tk

def serial_ports():
    for port in list('ABCDE'):
        yield port

OPTIONS = list(serial_ports())

class App(object):
    def __init__(self, master, **kwargs):
        self.master = master
        self.var = tk.StringVar()
        self.var.set('Port')
        self.option = tk.OptionMenu(master, self.var, *OPTIONS)
        self.option.pack()


root = tk.Tk()
app = App(root)
root.mainloop()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top