如何在tkinter中保存按钮命令的结果?

时间:2017-01-28 19:25:37

标签: python user-interface tkinter

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的字符串形式返回。

问题是,我如何使用用户输入的内容?该按钮不保存函数的返回值。

2 个答案:

答案 0 :(得分:1)

首先,您需要添加submitButton.pack()submitButton.grid()以显示tk窗口中的按钮。返回user_password不起作用,因为您没有为密码分配“命令”。您可以将功能更改为以下内容:

import tkinter as tk
from tkinter import simpledialog

def get_pass():
    global user_password
    user_password = simpledialog.askstring("Password Entry", "Enter your password here:")
    content.destroy()

content=tk.Tk()
submitButton = tk.Button(content, text="Start", command=get_pass)
submitButton.config(height=6, width=25, fg='red') #looks a little nicer
submitButton.pack()
content.mainloop()

#Do stuff with user_password
#print(user_password)

稍后打印user_password时,将显示通过simpledialog输入的密码。密码现在是user_password。

答案 1 :(得分:1)

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())