How to bind Tkinter destroy() to a key in Debian?

前端 未结 3 2013
余生分开走
余生分开走 2020-12-22 05:08

The following code works correctly in MS Windows (the script exits when pressing q):

import Tkinter as tk

class App():
    def __init__(self):
         


        
相关标签:
3条回答
  • 2020-12-22 05:49

    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
    
    class App():
        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()
    
        def q_pressed(self, event):
            print "q_pressed"
            self.root.destroy()
    
        def appexit(self):
            print "appexit"
            self.root.destroy()
    
    App()
    
    0 讨论(0)
  • 2020-12-22 05:59

    This usually works for me:

    def appexit(self, event):
        self.root.quit() # end mainloop
        self.root.destroy()
    
    0 讨论(0)
  • 2020-12-22 06:13

    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.

    0 讨论(0)
提交回复
热议问题