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

前端 未结 3 2028
余生分开走
余生分开走 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条回答
  •  Happy的楠姐
    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()
    

提交回复
热议问题