import tkinter as tk
from tkinter import simpledialog
def get_pass():
user_password = simpledialog.askstring("Password Entry", "Enter your password here:")
return user_password
submitButton = tk.Button(content, text="Start", command=get_pass)
#now I want to work with the password that the user entered.
用户应该点击“开始”按钮。单击按钮后,会出现一个 tkinter 消息框,要求用户输入密码。用户输入密码并提交。根据上面的代码,密码以名为 user_password 的字符串形式返回。
问题是,我如何使用用户输入的内容?按钮不保存函数的返回值。
请您参考如下方法:
command= 无法接收从 get_pass() 返回的值,因此您可以使用 global 变量(或 StringVar) 来分配 user_password。或者直接在 get_pass() 中使用这个值来检查密码,你将不必返回它。
import tkinter as tk
from tkinter import simpledialog
def get_pass():
# inform function to use external/global variable when you use `=`
global user_password
# `user_password_var` is global variable too
# but it doesn't need `global user_password_var`
# because it doesn't need `=` to assign value.
result = simpledialog.askstring("Password Entry", "Enter your password here:")
user_password = result
# or
user_password_var.set(result)
# or
if result != '123456':
label['text'] = "ERROR: password is incorrect"
else:
label['text'] = "password is OK"
# --- main ---
root = tk.Tk()
# it creates global variable
user_password = ''
# or
user_password_var = tk.StringVar()
label = tk.Label(root)
label.pack()
submitButton = tk.Button(root, text="Start", command=get_pass)
submitButton.pack()
# both variables are empty before `mainloop`
root.mainloop()
# both variables have value after `mainloop`
# print after you exit program
print(user_password)
print(user_password_var.get())
