#!/usr/bin/env python3 import tkinter as tk def release_and_exit(event=None): try: root.grab_release() except tk.TclError: # The XKB grab-breaking action may already have released the grab. pass root.destroy() def grab_mouse(): root.grab_set_global() status.config(text="Mouse grabbed. Test the XKB ungrab action.") grab_button.config(state=tk.DISABLED) root = tk.Tk() root.title("Mouse Grab Test") root.geometry("420x140") root.protocol("WM_DELETE_WINDOW", release_and_exit) root.bind("", release_and_exit) status = tk.Label( root, text="Click the button to globally grab the mouse.", padx=20, pady=20, ) status.pack() grab_button = tk.Button(root, text="Grab mouse", command=grab_mouse) grab_button.pack() tk.Label(root, text="Press Escape to release the grab and exit.").pack(pady=10) root.mainloop()