Tkinter:如何将参数从入口传递到函数(以及退出时的故障)

时间:2019-04-08 22:48:29

标签: python python-3.x tkinter

我一直在Tkinter的登录页面上工作,但是我无法创建一个功能来检查条目并将它们与特定输入进行比较。此外,该代码还会在每次退出窗口时添加一个消息框并调用一个函数。

我的代码是:

from tkinter import *
from tkinter import messagebox


root = Tk()
root.title("Login")



def makeUname(d):
    if messagebox.askyesno("Submit?", "Is this correct?"):
        global password
        username = uname.get()
        uname.grid_forget()
        return password

def makePasswd(d):
    if messagebox.askyesno("Submit?", "Is this correct?"):
        global username
        password = uname.get()
        passwd.grid_forget()
        return username

def button():
    makeUname("")
    makePasswd("")
    quitbutt.grid_forget()


uname = Entry(root)
uname.grid(row=1, column=1)

passwd = Entry(root, show="*")
passwd.grid(row=2, column=1)

quitbutt = Button(root, text="Login", command=button)
quitbutt.grid(row=3, column=1,  columnspan=2, sticky='nesw')


root.mainloop()

makeUname("")
makePasswd("")

if(username == "username" and password == "password"):
    messagebox.showwarning("Warning", "Sorry, this isn't programmed yet.")
else:
    messagebox.showwarning("Nope", "Nope. Nice try.")

有人可以帮助我提供我的代码吗?我应该使用其他设置或方法吗?

1 个答案:

答案 0 :(得分:1)

有很多问题,所以我更改了所有内容以使其更简单。

我在代码中添加了注释,以解释一些元素。

from tkinter import *
from tkinter import messagebox

# --- functions ---

def button():
    # use global variable (instead of local variables) 
    # to keep username, password outside function and keep after closing window
    global username
    global password

    username = uname.get()
    password = passwd.get()
    #print('button:', username, password)

    if username == "username" and password == "password":
        messagebox.showwarning("Warning", "Sorry, this isn't programmed yet.")
        root.destroy() # close window
    else:
        messagebox.showwarning("Nope", "Nope. Nice try.")
        # window still open

# --- main ---

# default values at start 
# Someone can exit window without using Button
# and it would not create this variables in button()
username = ""
password = ""

root = Tk()
root.title("Login")

uname = Entry(root)
uname.grid(row=1, column=1)

passwd = Entry(root, show="*")
passwd.grid(row=2, column=1)

quitbutt = Button(root, text="Login", command=button)
quitbutt.grid(row=3, column=1, columnspan=2, sticky='nesw')

# start program (start engine, display window, (re)draw widgets, handle events, get events from system (keyboard, mouse), send events to widgets)
root.mainloop()

# after closing window this variables still have values from window
print("after mainloop:", username, password)