Python,Tkinter登录框,无法使用户名和密码全局?

时间:2016-11-24 10:26:32

标签: python tkinter

我的代码看起来像这样,我认为全局用户名和全局密码可以工作,而不是打印用户名/密码,它打印的内容类似于“.41238472L”。我该如何解决?感谢

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

2 个答案:

答案 0 :(得分:2)

小部件需要父级存在。即使变量持有小部件实例,如果所述小部件的父级被破坏,也不能使用其方法。因此,在销毁root后,您无法获取内容条目。 可以StringVar绑定到Entry并获取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()

答案 1 :(得分:1)

您必须更改变量名称,因为现在您对两个不同的东西使用相同的名称。然后,您可以将文本从条目复制到变量。

import Tkinter as tk

# --- functions ---

def get_name():
    # inform function to use global variables instead of local one
    global username
    global password

    # copy values
    username = entry_username.get()
    password = entry_password.get()

    root.destroy()

# --- main ---

# global variable

username = None
password = None

# GUI

root = tk.Tk()

label_username = tk.Label(root, text="Enter Username")
entry_username = tk.Entry(root, bd=5)
label_password = tk.Label(root, text="Enter Password" )
entry_password = tk.Entry(root, bd=5, show='*')
submit = tk.Button(root, text="Submit", command=get_name)

label_username.pack()
entry_username.pack()
label_password.pack()
entry_password.pack()
submit.pack(side=tk.BOTTOM)

root.mainloop()

# result

print username
print password