Skip to content Skip to sidebar Skip to footer

How To Bind Tkinter Destroy() To A Key In Debian?

The following code works correctly in MS Windows (the script exits when pressing q): import Tkinter as tk class App(): def __init__(self): self.root = tk.Tk()

Solution 1:

With overrideredirect program loses connection with window manage so it seems that it can't get information about pressed keys and even it can't be focused.

MS Windows is one big window manager so it seems that overrideredirect doesn't work on that system.

Maybe you could use self.root.attributes('-fullscreen', True) in place of self.root.overrideredirect(True)


BTW: for testing I use self.root.after(5000, self.root.destroy) - to kill window after 5s when I can't control it.


EDIT:

Some (working) example with fullscreen.

With overrideredirect on Linux program can get keyboard events so binding doesn't work, and you can't focus Entry(). But mouse and Button() works. overrideredirect is good for "splash screen" with or without buttons.

import Tkinter as tk

classApp():
    def__init__(self):
        self.root = tk.Tk()

        # this works

        self.root.attributes('-fullscreen', True)

        # this doesn't work#self.root.overrideredirect(True)#self.root.geometry("800x600+100+100") # to see console behind#self.root.after(5000, self.appexit) # to kill program after 5s

        self.root.bind('q', self.q_pressed)

        tk.Label(text="some text here").grid()
        e = tk.Entry(self.root)
        e.grid()
        e.focus() # focus doesn't work with overrideredirect 

        tk.Button(self.root, text='Quit', command=self.appexit).grid()

        self.root.mainloop()

    defq_pressed(self, event):
        print"q_pressed"
        self.root.destroy()

    defappexit(self):
        print"appexit"
        self.root.destroy()

App()

Solution 2:

If a key binding doesn't work, it is likely that the window to which the binding is associated doesn't have the keyboard focus. In your situation with no window manager, your program probably doesn't have keyboard focus.

You might try forcing it to have focus with root.focus_force(). This will sometimes give focus to a window even when the application as a whole isn't the foreground app. This is somewhat depending on the window manager, or lack thereof.

Solution 3:

This usually works for me:

defappexit(self, event):
    self.root.quit() # end mainloopself.root.destroy()

Post a Comment for "How To Bind Tkinter Destroy() To A Key In Debian?"