Python 在tkinter中,如何将entry函数赋值给变量

Python 在tkinter中,如何将entry函数赋值给变量,python,user-interface,python-3.x,tkinter,Python,User Interface,Python 3.x,Tkinter,我试图在if语句中使用它来检查用户名是否等于接受的答案。我在ent_用户名上使用了.get(),试图选择名称,但没有成功。是不是它从来没有真正得到输入作为用户名,我需要做更多的代码与按钮。请帮忙 import tkinter action = "" #create new window window = tkinter.Tk() #name window window.title("Basic window") #window sized window.geometry("250x200")

我试图在if语句中使用它来检查用户名是否等于接受的答案。我在ent_用户名上使用了.get(),试图选择名称,但没有成功。是不是它从来没有真正得到输入作为用户名,我需要做更多的代码与按钮。请帮忙

import tkinter
action = ""
#create new window
window = tkinter.Tk()

#name window
window.title("Basic window")

#window sized
window.geometry("250x200")

#creates label then uses ut
lbl = tkinter.Label(window, text="The game of a life time!", bg="#a1dbcd")

#pack label
lbl.pack()

#create username
lbl_username = tkinter.Label(window, text="Username", bg="#a1dbcd")
ent_username = tkinter.Entry(window)

#pack username
lbl_username.pack()
ent_username.pack()
#attempting to get the ent_username info to store
username = ent_username.get()

#configure window
window.configure(background="#a1dbcd")

#basic enter for password
lbl_password = tkinter.Label(window, text="Password", bg="#a1dbcd")
ent_password = tkinter.Entry(window)

#pack password
lbl_password.pack()
ent_password.pack()
#def to check if username is valid
def question():
    if username == "louis":
        print("you know")
    else:
        print("failed")

#will make the sign up button and will call question on click
btn = tkinter.Button(window, text="Sign up", command=lambda: question())

#pack buttons
btn.pack()

#draw window
window.mainloop()

最简单的方法是将变量与条目小部件相关联。对于变量,您必须使用其中一个,并且它必须是与该类小部件关联的tkinter变量。对于Entry小部件,您需要一个Stringvar。请参阅Effbot的第三方

在事件处理程序
question
中,您可以访问Tkinter变量的值

if username.get() == name_you_want:
    print "as expected"
处理函数名
question
命令
参数的正确值,正如萨默斯所说:

btn = tkinter.Button(window, text="Sign up", command=question)

您的问题是,在创建条目小部件时,您试图
获取条目小部件的内容。这永远是空字符串。您需要在函数内部移动
.get()
,以便在单击按钮时获取值

def question():
    username = ent_username.get() # Get value here
    if username == "louis":
        print("you know")
    else:
        print("failed")
或者
如果ent\u username.get()=“louis”:

您确实可以选择使用
StringVar
,但我从未发现有必要使用它,除非使用OptionMenu小部件

另外,还有几个旁注。使用
命令
参数时,传入变量时只需
lambda
,只需确保删除
()

通常的做法是
将tkinter作为tk导入。这样,您就不会在所有内容前面加上
tkinter
,而是
tk
。它只是节省了打字和空间。看来是这样,

ent_username = tk.Entry(window)
btn = tkinter.Button(window, text="Sign up", command=question)
ent_username = tk.Entry(window)