简体   繁体   中英

Close main Tkinter window binding a key

I do not understand why this code does not work:

import tkinter

class Application ():

def__init__(self):

        self.master = tkinter.Tk()
        self.master.bind("<Enter>", self.quit)
        self.master.mainloop()

    def quit (self):
        self.master.destroy()

my_app = Application()

I keep receiving the error: "quit() takes 1 positional argument but 2 were given". Is there a way to close a main Tkinter window binding a key?

Thanks

Simply add another variable to the quit method ("i","n",etc.), when you bind an event to a method, the method must be able to handle said event as a parameter.

import tkinter

class Application ():

    def __ init __ (self):

       self.master = tkinter.Tk()
       self.master.bind("<Enter>", self.quit)
       self.master.mainloop()

    def quit (self,n):
       self.master.destroy()

#notice that the n variable doesnt really do anything other than "handling" of the event, so when
#it gets 2 arguments it can handle 2 parameters without giving an exception
#the (old) method only had space for 1 argument (self), but the moment you "bind" a button or event
#the method MUST be able to handle such information

my_app = Application()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM