[英]Populate Tkinter OptionMenu with list of unknown length, i.e. list of serial ports
我正在研究一個Python程序,它將數據從串口記錄到.txt文件。 該程序使用Tkinter的OptionMenu來詢問用戶使用什么串口。 端口列表如下:
def serial_ports():
for port in list_ports.comports():
yield port
OPTIONS = list(serial_ports())
然后程序生成OptionMenu(窗口名稱='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)
我隨后得到了要打印的項目,但我找不到在OptionMenu中獲取它們的方法。 代碼如:
for n in OPTIONS:
#tried different things here: count, n = item, et whatever crazy stuff one tries.
w = apply(OptionMenu, (c, var, OPTIONS[n]))
沒有解決問題。
最后的想法是所選擇的OptionMenu返回串口的名稱,最好是字符串(不是索引)。 將插入:
ser0 = serial.Serial(port = '[HERE!!!]', baudrate = 9600, timeout = 0.5)
PS。 目前,該程序是使用Python 2.7.1為Mac OS X編寫的。
要使用列表OPTIONS
中的所有選項創建OptionMenu,請使用:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.