I want to detect if Ctrl + X is clicked so that I can exit my Python application. I don't know how to do it? Please help.
Asked
Active
Viewed 4,117 times
-1
-
What have you tried so far? What kind of application? Command line or gui based? – Alex Aug 21 '18 at 10:24
-
@alex As of now, I have a command line program. – alyssaeliyah Aug 21 '18 at 10:27
-
Standard behaviour on linux and macos is to stop things in the command line with Ctrl+C. Why do you want to switch to Ctrl+X? – Alex Aug 21 '18 at 10:29
-
@Alex -- Because it is a requirement of our teacher as pat of our assignment. – alyssaeliyah Aug 21 '18 at 10:31
-
Ok, and what have you tried so far? – Alex Aug 21 '18 at 10:32
2 Answers
1
Have you thought about using a function like the ones discussed here? Python read a single character from the user
Or maybe you could use curses.
Either way you would just need to find the key code for ctrl-X, it's 24.

onlynx76
- 11
- 3
0
The simple and the best option is to use the module keyboard
. Install it using pip install keyboard
.
Use the following code at the start of your code:
import keyboard as k
k.add_hotkey("ctrl+x",lambda: quit())
#Your code....
Well, it works easily, but, it will read keys from the whole windows. For example the program is running and you are using notepad currently and you pressed ctrl+x , then the python program will close too.

Nouman
- 6,947
- 7
- 32
- 60
-
Requires ROOT ... `raise OSError("Error 13 - Must be run as administrator")` – Yzmir Ramirez Apr 26 '20 at 00:59
-