darrenvba darrenvba - 14 days ago 8
Python Question

Python, Tkinter log in box, unable to make username and password global?

My code looks like this, I thought global username and global password would work, instead of printing the username/password it prints something similar to ".41238472L". How do I fix this? Thanks

from Tkinter import *

global username
global password
root = Tk()

def getName():
root.destroy()

userLabel = Label(root, text="Enter Username")
username = Entry(root, bd=5)
pwLabel = Label(root, text="Enter Password" )
password = Entry(root, bd=5, show ='*')
submit = Button(root, text ="Submit", command = getName)

userLabel.pack()
username.pack()
pwLabel.pack()
password.pack()
submit.pack(side = BOTTOM)
root.mainloop()

print username
print password

Answer

Widgets need a parent to exist. Even if a variable holds a widget instance, if that parent of said widget destroyed, you can not use its methods. So you can not get contents entries after destroying root. But you can bind a StringVar to Entry and get contents of StringVar.

from Tkinter import *

root = Tk()    
nameVar = StringVar()
passVar = StringVar()

def getName():
    root.destroy()

userLabel = Label(root, text="Enter Username")
username = Entry(root, bd=5, textvariable=nameVar)
pwLabel = Label(root, text="Enter Password" )
password = Entry(root, bd=5, textvariable=passVar, show ='*')
submit = Button(root, text ="Submit", command = getName)

userLabel.pack()
username.pack()
pwLabel.pack()
password.pack()
submit.pack(side = BOTTOM)
root.mainloop()

print nameVar.get()
print passVar.get()