如果在相应的输入框中没有输入任何内容,我该如何修改此程序,使其不包含“路点”的任何信息?换句话说,“数据”具有树部分,但如果没有输入任何内容,例如E2,我希望数据为[ { 'Way point1':(2,E1.get()), 'c':3.0 } ]
from Tkinter import *
import json
top = Tk()
L1 = Label(top, text="Way point1")
L1.pack()
E1 = Entry()
E1.pack()
L2 = Label(top, text="Way point2")
L2.pack()
E2 = Entry()
E2.pack()
def printout():
data = [ { 'Way point1':(2,E1.get()), 'Way point2':(2, E2.get()), 'c':3.0 } ]
print json.dumps(data, sort_keys=True, indent=2)
plus = Button(top, text='+', command=printout).pack(side=LEFT)
top.mainloop()
答案 0 :(得分:1)
仅使用2个航点,只需使用if
语句:
waypoints = {'c': 3.0}
if E1.get():
waypoints['Way point1']: (2, E1.get())
if E2.get():
waypoints['Way point2']: (2, E2.get())
data = [waypoints]
答案 1 :(得分:1)
如果您计划将来添加额外的航点,您可以将其构建到一个列表中进行迭代:
from Tkinter import *
import json
E = []
L = []
top = Tk()
number_of_waypoints = 2
for n in range(1, number_of_waypoints+1): #+1 as 1...N
l = Label(top, text="Way point%d" % n)
l.pack()
e = Entry()
e.pack()
E.append(e)
L.append(l)
def printout():
# Iterate over the zip of E & L (joined), building the dict using .cget('text') to get
# the value of the Tkinter label. Add the { 'c':3.0 } to the end of the resulting list
data = [ { l.cget("text"): (2,e.get()) } for e,l in zip(E,L) ] + [{ 'c':3.0 }]
print json.dumps(data, sort_keys=True, indent=2)
plus = Button(top, text='+', command=printout).pack(side=LEFT)
top.mainloop()