-1

如果在相应的输入框中没有输入任何内容,我该如何修改这个程序,使其不包含有关“航点”的任何信息?换句话说,“数据”有树部分,但如果在例如 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()
4

2 回答 2

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]
于 2013-04-14T11:59:19.840 回答
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()
于 2013-04-14T12:08:21.453 回答