Search code examples
pythonpython-3.xtkinterkey-bindings

How to remove a keybind after it has done its job


I created a keybind, and want to delete it after it is activated. How do I do this?

I have tried this in my code:

def testing(event):
    print("Hello!")

root.bind_all('<Key>', testing)
root.deletecommand('<Key>', testing)

However, this does not work, as Python displays an error message stating that deletecommand() takes 2 positional arguments but 3 were given, when I only gave two arguments. I also tried root.delete('<Key>', testing), but this also fails.

from tkinter import *

def testing(event):
    print("Hello!")

root.bind_all('<Key>', testing)
root.deletecommand('<Key>', testing)

root.pack()
root.mainloop()

I was hoping that the program would remove the keybind after it did its job. However, Python displayed an error message, as mentioned before. How do I fix this problem?


Solution

  • try as this

    from tkinter import *
    root = Tk()
    
    
    def testing(event):
        print("Hello!")
        root.unbind_all('<Key>')
    
    
    root.bind_all('<Key>', testing)
    root.mainloop()
    

    For unbind all the widget use the function .unbind_all('<Key>').