Tkinter窗口绑定在返回'之后停止工作。

时间:2015-04-07 14:59:51

标签: python python-3.x tkinter

我当前有一个绑定到窗口的事件,以便在按下回车键时调用checkPassword()。这样可以正常工作,但是当调用checkPassword()时,事件仍然被绑定,因此使用回车键清除错误框时,如果将条目留空,则无法正常工作。

 def logIn():
        usernameLabel = Label(frame, text = 'Username: ')
        passwordLabel = Label(frame, text = 'Password: ')
        usernameEntry = Entry(frame)
        passwordEntry = Entry(frame, show="*")
        Button1 = Button(frame, text = 'Log in', command = lambda: checkPassword(usernameEntry, passwordEntry))
        usernameLabel.pack()
        usernameEntry.pack()
        passwordLabel.pack()
        passwordEntry.pack()
        Button1.pack(side=RIGHT)
        window.bind("<KeyRelease-Return>", lambda event: checkPassword(usernameEntry, passwordEntry))

    def checkPassword(usernameEntry, passwordEntry):
        username = usernameEntry.get()
        password = passwordEntry.get()
        if username == '':
            box.showerror('Error', 'Field can not be blank')
            return
        elif password == '':
            box.showerror('Error', 'Field can not be blank')
            return
        else:
            # do something

    from tkinter import *
    import tkinter.messagebox as box
    window = Tk()
    frame = Frame(window)
    logIn()
    frame.pack()
    window.mainloop()

为了解决这个问题,我尝试在checkPassword函数中解除窗口事件的绑定,这也有效,但是在返回logIn()后,logIn()中的窗口绑定不再有效? (其他一切如按钮功能正常)。

def checkPassword(usernameEntry, passwordEntry):
    window.unbind("<KeyRelease-Return>")

1 个答案:

答案 0 :(得分:1)

而不是

<KeyRelease-Return>

尝试使用:

<Return>

正在触发release绑定,因为按键关闭对话框,然后释放再次触发绑定。