Tkinter:从Entry小部件中获取数据

时间:2013-09-05 12:47:48

标签: python tkinter

我正在使用Python 2.7。这是较长程序的初始部分。我想要做的是添加一个新的用户名,以及身高和体重。我使用.txt文件来存储用户数据

示例userlist3.txt

add_new_user 1 1

unknown_user 170 70

monthy 185 83

[empty line]

这是代码:

from Tkinter import *
user_list = Tk()
user_list.title('Users')

def add_new_user():
    global select
    global height
    global weight 
    select = name.get()
    height = h.get()
    weight = w.get()   
    f = ' '
    us=open("userlist3.txt","a")
    print name, height, weight
    us.write(select + f + str(height) + f + str(weight) + "\n")
    us.close()
#    add_user.destroy() # it doesn't work
    user_list.destroy()

def onSelect(ev): # (10)
    global select
    select=listb.get(listb.curselection()) # (12)
    lab.configure(text=select) # (14)
    global name
    global h
    global w
    if select == 'add_new_user':
        add_user = Tk()
        add_user.title('New user')
        a=Label(add_user,text="Your username").pack()
        name = StringVar()
        NAME = Entry(add_user,textvariable = name).pack()
        b=Label(add_user,text="Your height (in cm)").pack()    
        h = IntVar()
        H = Entry(add_user,textvariable = h).pack()
        c=Label(add_user,text="Your weight (in kg)").pack()
        w = IntVar()
        W = Entry(add_user,textvariable = w).pack()
        Add_New_User=Button(add_user,text="Add new user data",command=add_new_user).pack()
        add_user.mainloop()
    else:
        user_list.destroy()

a=open("userlist3.txt","r")
b =[]
for linea in a:
    b.append(linea)
a.close()
e = []
for i in range(len(b)):
    e.append(b[i].split())
userlist = []
heightlist = []
weightlist = []
for i in range(len(e)):
    userlist.append(e[i][0])
    heightlist.append(e[i][1])
    weightlist.append(e[i][2]) 

sbar = Scrollbar(user_list, orient=VERTICAL) # (20)
listb = Listbox(user_list, width=30, height=4) # (22)
sbar.config(command=listb.yview) # (30)
listb.config(yscrollcommand=sbar.set) # (32)
sbar.pack(side=RIGHT, fill=Y) # (40)
listb.pack() # (42)
lab=Label(user_list,text="Double Click on User") # (50)
lab.pack()
for c in userlist: listb.insert(END,c)
listb.bind('<Double-1>',onSelect) # (70)
user_list.mainloop()

for d in range(1,len(userlist)):
    if userlist[d] == select:
        height = int(heightlist[d])
        weight = int(weightlist[d])

print "Selected user is: ",select
print height
print weight

它适用于已存在于txt文件中的用户,但如果我想添加新文件则不行。当我尝试时,我在shell上打印了'PY_VAR0 0 0',并在txt文件的新行中添加了'' 0 0。显然,这些数据在我的软件的以下步骤中没用。我可能在某处错过了.get()

2 个答案:

答案 0 :(得分:0)

当您看到类似PY_VAR0的内容时,这意味着您要打印出StringVar(或IntVar或其他)的实例,而不是打印出变量的。如果您使用的是特殊变量之一,则必须调用get()方法来获取值。

在您的具体情况下,请更改此内容:

print name, width, height

对此:

print name.get(), width, height

答案 1 :(得分:0)

感谢Fiver的建议! metaphy的解决方案有效,我解决了在

中修改第28行的问题

add_user = Toplevel(user_list)