XaviPacheco
Posts: 28
Joined: Fri May 11, 2018 1:41 pm

Binding Escape key in Tkinter GUI.

Mon Oct 15, 2018 2:38 am

For example, I usually see this:

Code: Select all

import Tkinter as tk
def exit():
    root.destroy()
root = tk.Tk()
root.bind("<Escape>", exit)
root.mainloop()
But this doesn't work in my program. Any ideas?

scotty101
Posts: 3178
Joined: Fri Jun 08, 2012 6:03 pm

Re: Binding Escape key in Tkinter GUI.

Mon Oct 15, 2018 8:51 am

Your code raised the following error for me

Code: Select all

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\....\lib\tkinter\__init__.py", line 1702, in __call__
    return self.func(*args)
TypeError: exit() takes 0 positional arguments but 1 was given
If you bind an event, it will pass event information to the function meaning that the function should expect at least 1 argument.

I changed the function code to the following and it worked as expected.

Code: Select all

def exit(e):
    root.destroy()
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

XaviPacheco
Posts: 28
Joined: Fri May 11, 2018 1:41 pm

Re: Binding Escape key in Tkinter GUI.

Mon Oct 15, 2018 12:27 pm

Still doesn't work. I don't understand what's going on. It doesn't throw errors. It simple doesn't respond to Esc press.

scotty101
Posts: 3178
Joined: Fri Jun 08, 2012 6:03 pm

Re: Binding Escape key in Tkinter GUI.

Mon Oct 15, 2018 1:27 pm

Have you tried clicking on the window that appears to ensure that it has "focus"?

You could try the following line of code to force focus before the mainloop line

Code: Select all

root.focus_set()
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

XaviPacheco
Posts: 28
Joined: Fri May 11, 2018 1:41 pm

Re: Binding Escape key in Tkinter GUI.

Mon Oct 15, 2018 10:58 pm

I found where my problem is. I was using root.overrideredirect(1) to hide the task bar. If I remove the override, the Esc key works well. Isn't there another way to hide the task bar to show the GUI in full screen?

XaviPacheco
Posts: 28
Joined: Fri May 11, 2018 1:41 pm

Re: Binding Escape key in Tkinter GUI. (SOLVED)

Mon Oct 15, 2018 11:13 pm

This worked for me:

Code: Select all

import tkinter as tk

def exit(event):
    root.destroy()
    
root = tk.Tk()

root.attributes("-fullscreen", True)
root.wm_attributes("-topmost", 1) # keep on top

root.bind("<Escape>", exit)
root.mainloop()

Return to “Beginners”