I am making an interface to display available com ports as buttons and, when pressed to pass the com name to a variable. Currently I can make dynamic buttons but I am having trouble passing the values to an outside function.
The code creates two buttons for com7 and com8 (current ports on my system) with a dictionary in which i[1]=com7 and i[2]=com8. When I press the button for i[1] I get a Keyerror because the current value of K is now 3, which is not a key in the dictionary. Obviously I want the button to reference the value of K when it was created, not the current value of K.
Essentially I want python to evaluate i[k] at the moment of button creation, not at the moment the button is pressed.
import serial, sys, os, Tkinter
from Tkinter import *
def com():
global ser
global p
def pget(inport):
print inport
test.destroy()
test=Tk()
try:
from serial.tools.list_ports import comports
except ImportError:
comports = None
V = ""
while V is "" :
for port, desc, hwid in sorted(comports()):
print "\nAvailable Ports:\n"
V =sys.stderr.write(' %-10s %s\n' % (port, desc))
if V is "":
print "No ports available, plug in COM port and hit ENTER"
raw_input()
def Port():
i={}
k=1
if comports:
l=Label(test, text="Available ports:").pack(side=TOP)
sys.stderr.write('\n Available ports:\n')
for port, desc, hwid in sorted(comports()):
print port
i[k]=port
bport=Button(test,text=port+": "+desc,command=lambda: pget(i[k])).pack()
print k, i[k]
k+=1
test.mainloop()
Port()
com()