Search code examples
pythontkinterkey

Add event for 'windows' button in tkinter?


My Code:

from tkinter import*
root = Tk()
root.geometry("500x500")
def moti(event):
    root.destroy()
root.bind("<Window>",moti)
root.mainloop()

I want to bind this keyenter image description here

So,how can I bind This key in windows?Thank you!


Solution

  • From a practical example, I was able to find the windows key is called as <Win_L>(for the left key) <Win_R> for the right one), you can find that out yourself by using this code:

    import tkinter as tk
    
    root = tk.Tk()
    
    def event(e):
        print(e.keysym)
    
    root.bind('<Key>',event)
    root.mainloop()
    

    This will print the key name once the window has focus and you press on it.

    So TL;DR: The key name for the windows key is <Win_L>. Also for reference read keysyms manual page - Tk-built-in-commands

    w.bind('<Win_L>',callback)
    

    Note: While on Windows systems you can use <Win_L>, on a ubuntu system it would be <Super_L>. So a safe method would be:

    from tkinter import *
    
    root = Tk()
    
    def event(e):
        print(f'You just clicked: {e.keysym}')
    
    try:
        root.bind('<Win_L>',event)
    except TclError:
        root.bind('<Super_L>',event)
    
    root.mainloop()