1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| # -*- coding: utf-8 -*-
# Python 2 & 3
import time
import threading
try: # { v2
import Tkinter as tkinter
except: # v3
import tkinter
# }
def callback_bind_escape(event=None, *args): # event contient des informations sur la position souris, l'élément sélectionné/focused
global loop_status, t_main
loop_status = False
print("Boucle arrêtée")
t_main.join(timeout=0.1) # pour éviter "RuntimeError: main thread is not in main loop" après le destroy; si le thread essaie encore d'écrire dans le root
root.destroy()
return
def main():
global loop_status, label_var
loop_status = True
loop_iteration = 0
print("Appuyez sur Échap pour arrêter...")
while loop_status:
loop_iteration += 1
print(loop_iteration)
time.sleep(1)
return
if __name__ == "__main__":
root = tkinter.Tk()
root.bind('<Escape>', callback_bind_escape) # Escape key
t_main = threading.Thread(target=main)
t_main.start() # Non bloquant
root.mainloop() # Bloquant jusqu'au destroy()
print("Done") |
Partager