[英]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.