Exiting a tkinter app with Ctrl-C and catching SIGINT - python

Ctrl-C/SIGTERM/SIGINT seem to be ignored by tkinter. Normally it can be captured again with a callback. This doesn't seem to be working, so I thought I'd run tkinter in another thread since its mainloop() is an infinite loop and blocks. I actually also want to do this to read from stdin in a separate thread. Even after this, Ctrl-C is still not processed until I close the window. Here's my MWE:
#! /usr/bin/env python
import Tkinter as tk
import threading
import signal
import sys
class MyTkApp(threading.Thread):
def run(self):
self.root = tk.Tk()
self.root.mainloop()
app = MyTkApp()
app.start()
def signal_handler(signal, frame):
sys.stderr.write("Exiting...\n")
# think only one of these is needed, not sure
app.root.destroy()
app.root.quit()
signal.signal(signal.SIGINT, signal_handler)
Results:
Run the app
Ctrl-C in the terminal (nothing happens)
Close the window
"Exiting..." is printed and I get an error about the loop already having exited.
What's going on here and how can I make Ctrl-C from the terminal close the app?
Update: Adding a poll, as suggested, works in the main thread but does not help when started in another thread...
class MyTkApp(threading.Thread):
def poll(self):
sys.stderr.write("poll\n")
self.root.after(50, self.poll)
def run(self):
self.root = tk.Tk()
self.root.after(50, self.poll)
self.root.mainloop()

here's a working example that catches control c in the windows or from the command line. this was tested with 3.7.2 this seems simpler than the other solutions. I almost feel like I'm missing something.
import tkinter as TK
import signal
def hello():
print("Hello")
root = TK.Tk()
TK.Button(root, text="Hi", command=(hello)).pack( )
def handler(event):
root.destroy()
print('caught ^C')
def check():
root.after(500, check) # time in ms.
# the or is a hack just because I've shoving all this in a lambda. setup before calling main loop
signal.signal(signal.SIGINT, lambda x,y : print('terminal ^C') or handler(None))
# this let's the terminal ^C get sampled every so often
root.after(500, check) # time in ms.
root.bind_all('<Control-c>', handler)
root.mainloop()

Since your tkinter app is running in another thread, you do not need to set up the signal handler in the main thread and just use the following code block after the app.start() statement:
import time
while app.is_alive():
try:
time.sleep(0.5)
except KeyboardInterrupt:
app.root.destroy()
break
You can then use Ctrl-C to raise the KeyboardInterrupt exception to close the tkinter app and break the while loop. The while loop will also be terminated if you close your tkinter app.
Note that the above code is working only in Python 2 (as you use Tkinter in your code).

Proper CTRL-C & SIGINT Usage in Python
The problem is that you are exiting the main thread, so the signal handler is basically useless. You need to keep it running, in a while loop, or my personal preference, Events from threading module. You can also just catch the KeyboardInterrupt exception generated by the CTRL-C event, rather than dealing with signal handlers.
SIGINT in Tkinter
Using tkinter, you must have the tkinter app run in a separate thread, so that it doesn't interfere with the signal handler or KeyboardInterrupt exception. In the handler, to exit, you need to destroy then update tkinter root. Update allows the tkinter to update so that it closes, without waiting for mainloop. Otherwise, user has to click on the active window to activate mainloop.
# Python 3
from tkinter import *
from threading import Thread
import signal
class MyTkApp(Thread):
def run(self):
self.root = Tk()
self.root.mainloop()
def sigint_handler(sig, frame):
app.root.quit()
app.root.update()
app = MyTkApp()
# Set signal before starting
signal.signal(signal.SIGINT, sigint_handler)
app.start()
Note: SIGINTs can also be caught if you set handler in same thread as tkinter mainloop, but you need to make tkinter window active after the signal so that it's mainloop can run. There is no way around this unless you run in new thread.
More Information on Tkinter & Command Line Communication
For more on communicating between tkinter and the command line, see Using Tkinter Without Mainloop. Basically, you can use update method in your loop, and then communicate with other threads and processes, etc. I would personally NOT recommend this, as you are essentially doing the job of the python thread control system, which is probably opposite of what you want to do. (python has a process that runs all internal threads in one external thread, so you are not taking advantage of multitheading, unless using multiprocessing module)
# Python 2
from Tkinter import *
ROOT = Tk()
LABEL = Label(ROOT, text="Hello, world!")
LABEL.pack()
LOOP_ACTIVE = True
while LOOP_ACTIVE:
ROOT.update()
USER_INPUT = raw_input("Give me your command! Just type \"exit\" to close: ")
if USER_INPUT == "exit":
ROOT.quit()
LOOP_ACTIVE = False
else:
LABEL = Label(ROOT, text=USER_INPUT)
LABEL.pack()

Related

How do I exit my python3 application cleanly from asyncio event loop run_forever() when user clicks tkinter root window close box?

I'm trying to make a python3 application for my Raspberry Pi 4B and I have the tkinter windows working fine, but need to add asynchronous handling to allow tkinter widgets to respond while processing asynchronous actions initiated by the window's widgets.
The test code is using asyncio and tkinter. However, without root.mainloop(), since asyncio loop.run_forever() is called at the end instead. The idea is that when the user clicks the main window's close box, RequestQuit() gets called to set the quitRequested flag and then when control returns to the event loop, root.after_idle(AfterIdle) would cause AfterIdle to be called, where the flag is checked and if true, the event loop is stopped, or that failing, the app is killed with exit(0).
The loop WM_DELETE_WINDOW protocol coroutine RequestQuit is somehow not getting called when the user clicks the main window close box, so the AfterIdle coroutine never gets the flag to quit and I have to kill the app by quitting XQuartz.
I'm using ssh via Terminal on MacOS X Big Sur 11.5.2, connected to a Raspberry Pi 4B with Python 3.7.3.
What have I missed here?
(I haven't included the widgets or their handlers or the asynchronous processing here, for brevity, since they aren't part of the problem at hand.)
from tkinter import *
from tkinter import messagebox
import aiotkinter
import asyncio
afterIdleProcessingIntervalMsec = 500 # Adjust for UI responsiveness here.
busyProcessing = False
quitRequested = False
def RequestQuit():
global quitRequested
global busyProcessing
if busyProcessing:
answer = messagebox.askquestion('Exit application', 'Do you really want to abort the ongoing processing?', icon='warning')
if answer == 'yes':
quitRequested = True
def AfterIdle():
global quitRequested
global loop
global root
if not quitRequested:
root.after(afterIdleProcessingIntervalMsec, AfterIdle)
else:
print("Destroying GUI at: ", time.time())
try:
loop.stop()
root.destroy()
except:
exit(0)
if __name__ == '__main__':
global root
global loop
asyncio.set_event_loop_policy(aiotkinter.TkinterEventLoopPolicy())
loop = asyncio.get_event_loop()
root = Tk()
root.protocol("WM_DELETE_WINDOW", RequestQuit)
root.after_idle(AfterIdle)
# Create and pack widgets here.
loop.run_forever()
The reason why your program doesn't work is that there is no Tk event loop, or its equivalent. Without it, Tk will not process events; no Tk callback functions will run. So your program doesn't respond to the WM_DELETE_WINDOW event, or any other.
Fortunately Tk can be used to perform the equivalent of an event loop as an asyncio.Task, and it's not even difficult. The basic concept is to write a function like this, where "w" is any tk widget:
async def new_tk_loop():
while some_boolean:
w.update()
await asyncio.sleep(sleep_interval_in_seconds)
This function should be created as an asyncio.Task when you are ready to start processing tk events, and should continue to run until you are ready to stop doing that.
Here is a class, TkPod, that I use as the basic foundation of any Tk + asyncio program. There is also a trivial little demo program, illustrating how to close the Tk loop from another Task. If you click the "X" before 5 seconds pass, the program will close immediately by exiting the mainloop function. After 5 seconds the program will close by cancelling the mainloop task.
I use a default sleep interval of 0.05 seconds, which seems to work pretty well.
When exiting such a program there are a few things to think about.
When you click on the "X" button on the main window, the object sets its app_closing variable to false. If you need to do some other clean-up, you can subclass Tk and over-ride the method close_app.
Exiting the mainloop doesn't call the destroy function. If you need to do that, you must do it separately. The class is a context manager, so you can make sure that destroy is called using a with block.
Like any asyncio Task, mainloop can be cancelled. If you do that, you need to catch that exception to avoid a traceback.
#! python3.8
import asyncio
import tkinter as tk
class TkPod(tk.Tk):
def __init__(self, sleep_interval=0.05):
self.sleep_interval = sleep_interval
self.app_closing = False
self.loop = asyncio.get_event_loop()
super().__init__()
self.protocol("WM_DELETE_WINDOW", self.close_app)
# Globally suppress the Tk menu tear-off feature
# In the following line, "*tearOff" works as documented
# while "*tearoff" does not.
self.option_add("*tearOff", 0)
def __enter__(self):
return self
def __exit__(self, *_x):
self.destroy()
def close_app(self):
self.app_closing = True
# I don't know what the argument n is for.
# I include it here because pylint complains otherwise.
async def mainloop(self, _n=0):
while not self.app_closing:
self.update()
await asyncio.sleep(self.sleep_interval)
async def main():
async def die_in5s(t):
await asyncio.sleep(5.0)
t.cancel()
print("It's over...")
with TkPod() as root:
label = tk.Label(root, text="Hello")
label.grid()
t = asyncio.create_task(root.mainloop())
asyncio.create_task(die_in5s(t))
try:
await t
except asyncio.CancelledError:
pass
if __name__ == "__main__":
asyncio.run(main())

how to send event to main thread in jupyter notebook

I'm using threading and I want to start a tkinter loop within a secondary thread.
I've learnt that this causes troubles, and that tkinter should be run always in the main thread.
I wonder if it is possible to send ann event to the main thread from a secondary thread.
I've come with a solution like this, which involves sending a signal from the secondary thread setting a main class-variable, as a condition to run the code I want to be run in the main thread:
import threading as th
import tkinter as tk
class Interfaz:
def __init__(self):
self.lock=False
th.Thread(name='main_th',target=main).start()
while True:
if self.lock==False:
if 'main_th' not in [t.getName() for t in th.enumerate()]:
th.Thread(name='main_th',target=main).start()
else:
pass
else:
self.stkinter()
def main(self):
if user_click() == True:
self.lock==True
#send_tkinter_to_main_thread()...
else:
show_or_update_interfaz()
do_something_else()
def stkinter(self):
self.master=tk.Tk()
tk.Button(self.master,command=self.Done).grid()
self.master.mainloop()
def Done(self):
self.master.destroy()
self.lock=False
What I would like to do is to excecute 'stkinter' from 'main', sending it to the main thread... is that possible?

how to update tkinter gui label with a thread?

I am new to Python tkinter . I have written the following code for my gui . I want to update my label 1 with received body message from rabbitmq . But i am facing issue once my gui get populate after that even i receive different message in body ,but its not able to update . Once i am closing the gui then again its coming with new value. I want my gui tkinter window to be constant and label should be refreshed on receiving new message in body.
import tkinter
from PIL import ImageTk, Image as PILImage
import datetime as dt
from tkinter import *
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
global myval
print(" [x] Received %r" % body)
window=Tk()
window.attributes('-fullscreen',True)
window.bind("<F11>", lambda event: window.attributes("-fullscreen",
not window.attributes("-fullscreen")))
window.bind("<Escape>", lambda event: window.attributes("-fullscreen",False))
top_left=Frame(window,width=200,height=200)
top_middle=Frame(window,width=550,height=200)
top_right=Frame(window,width=250,height=200)
middle_left=Frame(window,width=200,height=300)
middle_middle=Frame(window,width=300,height=300)
middle_right=Frame(window,width=300,height=300)
bottom_left=Frame(window,width=0,height=200)
bottom_middle=Frame(window,width=300,height=200)
bottom_right=Frame(window,width=300,height=200)
top_left.grid(row=0,column=0)
top_middle.grid(row=0,column=1)
top_right.grid(row=0,column=2,sticky=E+W)
middle_left.grid(row=1,column=0,padx=100,pady=100)
middle_middle.grid(row=1,column=1)
middle_right.grid(row=1,column=2)
bottom_left.grid(row=2,column=0)
bottom_middle.grid(row=2,column=1)
bottom_right.grid(row=2,column=2)
dte=Label(top_left, text="Date: "f"{dt.datetime.now():%a,%d/ %m/ %Y}",fg="black",font=("Arial Bold ",12 ))
dte.place(x=0,y=40)
lbl=Label(top_middle, text="Welcome to Smartcards Division",fg='#3333ff',font=("Arial Bold Italic",24 ))
lbl.place(x=0,y=30)
logo_path="logo.jpg"
logo = ImageTk.PhotoImage((PILImage.open(logo_path)).resize((280,100),PILImage.ANTIALIAS))
logo_panel = Label(top_right,image = logo)
logo_panel.place(x=10,y=30)
string_clsname=str(body.decode())
lblxt=StringVar()
lbl1=Label(middle_left, textvariable=lblxt,fg='#ff6600',font=("Arial Bold Italic",16))
lblxt.set("Hello "+string_clsname+" Sir")
lbl1.place(x=0,y=100)
path = "NewPicture_Copy.jpg"
image = ImageTk.PhotoImage((PILImage.open(path)).resize((250,250),PILImage.ANTIALIAS))
panel = Label(middle_middle,image = image,borderwidth=5, relief="ridge")
panel.pack()
lbl2=Label(bottom_middle, text="\u00a9"+"2020-Smartcards Division",fg='black',font=("Helvetica",8))
lbl2.place(x=0,y=0)
window.title('Image Classification')
window.mainloop()
channel.basic_consume(
queue='hello', on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
At a base level, you need:
Separate threads of execution,
for separate tasks (that must run concurrently).
A way for the threads to communicate with each other;
while avoiding race conditions
(like modifying a variable in one thread,
while another thread is reading it).
Here you can e.g. use mutexes/locks, message-passing, etc.
import tkinter as tk
from collections import deque
from threading import Thread
from random import randint
from time import sleep
# Starting out (this is the main/gui thread).
root = tk.Tk()
label = tk.Label(root, text='Original text')
label.pack()
# Means of communication, between the gui & update threads:
messageQueue = deque()
# Create a thread, that will periodically emit text updates.
def emitText(): # The task to be called from the thread.
while(True): # Normally should check some condition here.
messageQueue.append(f'Random number: {randint(0, 100)}')
sleep(1) # Simulated delay (of 1 sec) between updates.
# Create a separate thread, for the emitText task:
thread = Thread(target=emitText)
# Cheap way to avoid blocking # program exit: run as daemon:
thread.setDaemon(True)
thread.start() # "thread" starts running independently.
# Moving on (this is still the main/gui thread).
# Periodically check for text updates, in the gui thread.
# Where 'gui thread' is the main thread,
# that is running the gui event-loop.
# Should only access the gui, in the gui thread/event-loop.
def consumeText():
try: label['text'] = messageQueue.popleft()
except IndexError: pass # Ignore, if no text available.
# Reschedule call to consumeText.
root.after(ms=1000, func=consumeText)
consumeText() # Start the consumeText 'loop'.
root.mainloop() # Enter the gui event-loop.
See also:
queue.Queue
"collections.deque is an alternative implementation of
unbounded queues with fast atomic append() and popleft()
operations that do not require locking."
collections.deque
threading.Thread

Python 3 - KeyboardInterrupt in background thread not detected by main thread until user hovers over GUI window

I've written a Python 3 TkInter-based GUI application that launches a worker thread in the background. After the worker thread has finished, it waits two seconds (this is to avoid a possible race condition), and then sends a KeyboardInterrupt to tell the main thread it can close down.
Expected behaviour: running the program launches a GUI window, prints some text to the console after which the program closes down automatically.
Actual behaviour: instead of closing automatically, it only does so after the user either hovers the mouse over the GUI window area, or presses a key on the keyboard! Apart from that the program runs without reporting any errors.
Anyone have any idea why this is happening, and how to fix this? I already tried to wrap the KeyboardInterrupt into a separate function and then call that through a timer object, but this results in the same behaviour.
I've been able to reproduce this issue on 2 different Linux machines that run Python 3.5.2. and 3.6.6 respectively.
#! /usr/bin/env python3
import os
import threading
import _thread as thread
import time
import tkinter as tk
import tkinter.scrolledtext as ScrolledText
class myGUI(tk.Frame):
# This class defines the graphical user interface
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.root = parent
self.build_gui()
def build_gui(self):
# Build GUI
self.root.title('TEST')
self.root.option_add('*tearOff', 'FALSE')
self.grid(column=0, row=0, sticky='ew')
self.grid_columnconfigure(0, weight=1, uniform='a')
# Add text widget to display logging info
st = ScrolledText.ScrolledText(self, state='disabled')
st.configure(font='TkFixedFont')
st.grid(column=0, row=1, sticky='w', columnspan=4)
def worker():
"""Skeleton worker function, runs in separate thread (see below)"""
# Print some text to console
print("Working!")
# Wait 2 seconds to avoid race condition
time.sleep(2)
# This triggers a KeyboardInterrupt in the main thread
thread.interrupt_main()
def main():
try:
root = tk.Tk()
myGUI(root)
t1 = threading.Thread(target=worker, args=[])
t1.start()
root.mainloop()
t1.join()
except KeyboardInterrupt:
# Close program if subthread issues KeyboardInterrupt
os._exit(0)
main()
(Github Gist link to the above script here)
root.mainloop() mainloop is blocking and pending (interceptable) signals in Python are only examined in between execution of bytecode instructions. t1.join() in your code actually never gets executed.
Since mainloop block-waits for forwarded hardware-interrupts, for unblocking you have to provide them by e.g. hovering over the window like you saw. Only then the interpreter detects the pending KeyboardInterrupt. That's just how signal processing in Python works.
Solving the general problem could mean finding ways to unblock blocking I/O-calls by externally injecting what's needed to unblock them, or just not using blocking calls in the first place.
For your concrete setup, you could kill the whole process with an unhandled SIGTERM, but of course, that would be very, very ugly to do and is also unnecessary here. If you just search for a way to timeout your window, you can timeout with the tkinter.Tk.after method (shown here and here), or you get rid of mainloop and run your loop yourself (here).
The latter could look like:
def main():
root = tk.Tk()
myGUI(root)
t1 = threading.Thread(target=worker, args=[])
t1.start()
while True:
try:
root.update_idletasks()
root.update()
time.sleep(0.1)
except KeyboardInterrupt:
print('got interrupt')
break
t1.join()

End python code without error keep Gui open

I have a tkinter gui that has a button that starts a process. During this process there is an if statement, if this statement is true then then the process ends. When the process ends I want the GUI to be kept open and not show an error. I've tried os._exit() but it closes the gui as well.
from Tkinter import *
import tkMessageBox
def Program():
#Process
#Process
if #something happens#:
#Stop process but keep gui open and dont show errors
root = Tk()
root.title("GUI")
root.geometry('450x300+200+200')
labelText=StringVar()
labelText.set("Program")
label1=Label(root,textvariable=labelText,height=4)
label1.pack()
mbutton=Button(text='Start Program',command=Model).pack()
root.mainloop()
You could run GUI in the main thread and put the part that should terminate independently in a background thread. Add try/except in the thread to suppress traceback e.g.:
import threading
def bgthread(gui_ready, result_queue):
gui_ready.wait()
while True:
try:
# do some work ...
result_queue.put(result) # GUI gets results e.g.,
# via q.get_nowait() in a
# widget.after() callback
if something_happened():
break # exit
except: #NOTE: don't use bare except unless it is absolutely necessary
logger.error() # log to file
break # exit
# setup logging
# ...
ready = threading.Event()
q = Queue.Queue()
threading.Thread(target=bgthread, args=(ready,q)).start()
# setup gui here
...
root.mainloop() # call ready.set() in some GUI code then it is ready
Python code worked using geo_pythoncl suggestion of using return.
from Tkinter import *
import tkMessageBox
def Program():
#Process
#Process
if #something happens#:
#Stop process but keep gui open and dont show errors
return
root = Tk()
root.title("GUI")
root.geometry('450x300+200+200')
labelText=StringVar()
labelText.set("Program")
label1=Label(root,textvariable=labelText,height=4)
label1.pack()
mbutton=Button(text='Start Program',command=Model).pack()
root.mainloop()

Categories

Resources