It may be done in Tk:
#!/usr/bin/wish
bind . <KeyPress> {puts "Key has been pressed"; exit; }
realpath /usr/bin/wish
/usr/bin/wish8.6
IMPORTANT NOTE: Key should be pressed in the Tk window, which will be opened after Tk script will start.
More complex solution address both parts of the question.
It is based on the following PyTk pytclsub.py script:
#!/usr/bin/python3.9
import tkinter as tk
import sys
import subprocess
import os
import signal
from pynput import keyboard
p = 0
def on_press(key):
print("Key pressed, exiting")
os.kill(p, signal.SIGINT)
os._exit(0)
listener = keyboard.Listener(on_press=on_press)
listener.start()
print("Started keyboard listener")
def run_process():
path = r"./mytcl.tcl"
p = subprocess.run(path)
root = tk.Tk()
log = tk.Text(root)
b = tk.Button(root, text="Run stuff", command=lambda: run_process())
log.pack()
b.pack()
root.mainloop()
TCL script mytcl.tcl
#!/usr/bin/tclsh
package require Tclx
while {1} {
sleep 1
puts "Waiting for keypress..."
}
Usage:
- Run
pytclsub.py script
- When main window will open, press Run stuff button
- Put mouse cursor within main window
- Press any key
Expected outcome: application will exit
Example of the output
pytclsub.py
Started keyboard listener
Waiting for keypress...
Waiting for keypress...
Waiting for keypress...
Key pressed, exiting