使用未知长度的列表填充Tkinter OptionMenu,即串行端口列表



我正在开发一个Python程序,该程序将数据从串行端口记录到.txt文件中。该程序使用Tkinter的选项菜单询问用户使用哪个串行端口。端口列表如下:

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

然后程序制作选项菜单(窗口名称 = '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)

我随后获取要打印的项目,但找不到在选项菜单中获取它们的方法。代码如下:

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

没有解决问题。

最后的想法是,选择的选项菜单返回 串行端口的名称 ,最好是字符串(而不是索引)。将插入:

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

附言。目前,该程序是为带有Python 2.7.1的Mac OS X编写的。

要使 OptionMenu 包含列表中的所有选项OPTIONS,请使用:

w =  OptionMenu(c, var, *OPTIONS)

例如

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()

最新更新