[英]In tkinter how do I assign the entry function to a variable
我试图在if语句中使用它来检查用户名是否等于接受的答案。 我在ent_username上使用.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()
您的问题是,在创建窗口小部件时,您试图get
其内容。 并且这将始终是空字符串。 您需要在函数内部移动.get()
,以便在单击按钮时获取值。
def question():
username = ent_username.get() # Get value here
if username == "louis":
print("you know")
else:
print("failed")
或者, if ent_username.get() == "louis":
您确实可以选择使用StringVar
但除OptionMenu小部件外,我从未发现需要使用它
另外,还有一些注意事项。 使用command
参数时,只需要在传递变量时使用lambda
,只需确保删除()
。
btn = tkinter.Button(window, text="Sign up", command=question)
通常的做法是import tkinter as tk
。 这样,您不会在所有内容前加上tkinter
前缀,而不会在tk
前面加上前缀。 它只是节省了键入和空间。 看起来像这样
ent_username = tk.Entry(window)
最简单的方法是将变量与Entry小部件关联。 对于变量,您必须使用Tkinter变量之一 ,并且它必须是与此类小部件关联的tkinter变量。 对于Entry小部件,您需要一个Stringvar。 有关Entry小部件的信息,请参见Effbot的第三方文档 。
username = tkinter.StringVar()
ent_password = tkinter.Entry(window, textvariable=username)
在事件处理程序question
,您可以访问Tkinter变量的值。
if username.get() == name_you_want:
print "as expected"
如萨默斯所说,该处理函数名称question
是command
参数的正确值:
btn = tkinter.Button(window, text="Sign up", command=question)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.