I encounter a problem that slows me down a lot in my development ..
Indeed, I can not update the Queue with the Threading module of python!
I have searched several sites, and I could not find fault that could prevent my variable from updating.
My tkinter button should allow me to run another python script. To do this, I use Threading so I can use the GUI without interrupting it.
I explain my problem:
My tkinter button should allow me to run another python script. To do this, I use Threading so I can use the GUI without it being interrupted. Another button should allow me to update the Queue, and this is what the action does not do.
My main script with Tkinter:
import Tkinter, cv2
from Tkinter import *
from threading import Thread
import threading, Queue
import pyautogui, os, time, urllib2, urlparse
import cv2
from yes2 import *
def print1():
global kill, q
kill = []
q = Queue.Queue()
q.put("True")
thread = Thread(target = main, args=(kill, q))
thread.start()
def stop():
global q
q.put("False")
print q.get()
root = Tkinter.Tk()
root.title('breakable')
bouton= Button(root, text="Run", command=print1)
bouton.grid(row=3, column=0)
bouton= Button(root, text="stop", command=stop)
bouton.grid(row=3, column=1)
root.mainloop()
I want to open this other script:
def main(kill, q):
while True:
try:
get = q.get(timeout=2)
print get
except Empty as error:
print("Error too many times")
The value that comes out is "True", but when I click on my stop button, which is supposed to update my Queue in "False", well it does nothing
Thanks in advance :)
It does update your Queue, but on the very next line you get the value out again. Remove the print q.get() from the "stop" function.
Related
I have plan to make a simple test with tkinter which will change the left text with new input.
But it seems threading is not easy as my thought. It still be hang after 2 times of input.
from tkinter import *
import threading
win = Tk()
label1 = Label(win, text="this is a test on the left")
label1.pack(side=LEFT)
label2 = Label(win, text="this is a test on the right")
label2.pack(side=RIGHT)
def set_text():
while(True):
content=input("let enter the substuition:")
label1.config(text = content)
win.after(100, set_text)
setTextthr=threading.Thread(target = set_text)
setTextthr.start()
win.mainloop()
It is very impressed if you can point out why it happened and how to fix.
Thanks
There are some unwritten rules about threading in combination with tkinter.
One of them is not to touch any widget outside of the thread of tkinter.
This line violates this rule.
label1.config(text = content)
In order to do this you can use a tkinter.StingVar which isn't directly in the main event loop of tkinter.
The call from inside the function to itself with after some time will create a new stack of a while-loops on top. Below you find a working example which has its limits. For another approach you can take a look at this or this.
from tkinter import *
import threading
win = Tk()
var = StringVar(value="this is a test on the left")
label1 = Label(win,textvariable=var)
label1.pack(side=LEFT)
label2 = Label(win, text="this is a test on the right")
label2.pack(side=RIGHT)
def set_text():
while(True):
content=input("let enter the substuition:")
var.set(content)
setTextthr=threading.Thread(target = set_text)
setTextthr.start()
win.mainloop()
The usual way to approach getting data from threads in an event-driven program (as it is with tkinter) is to use some update loop (.after) to schedule a check on the data container (queue.Queue or a simple list) that contains data from the thread. Then additionally check if the thread is alive at all, and if it is not you can stop the update loop because there is nothing to update anymore. Also use some flag (threading.Event) to stop the thread loop upon destroying the window. The only issue is that input is used which makes it so that at the end at least the Enter key has to be pressed.
The code example (explanation in code comments):
import tkinter as tk
import threading
import queue
# this is the function that will run in another thread
def ask_input(q): # argument is the queue
# here check if the event is set, if it is
# don't loop anymore, however it will still wait
# for input so that has to be entered and
# then the thread will stop
while not event.is_set():
user_input = input('New content: ')
# put the user entered data into the queue
q.put(user_input)
# the function that will update the label
def update_label(q, t): # pass in the the queue and thread
# this loop simply gets the last item in the queue
# otherwise (not in this case perhaps) it may be a little
# too slow in updating since it only runs every 100 ms
# so it need to catch up
while not q.empty():
# get data from the queue
text = q.get()
# here it is save to update the label since it is the same
# thread where all of the tkinter runs
label.config(text=text)
# check if thread still runs (in this case this specific check
# is unnecessary since the thread is stopped only after
# the main window is closed)
if t.is_alive():
# schedule the next call with the same queue and thread
root.after(100, update_label, q, t)
# the function that initiates the thread
def start_thread():
# create a queue to pass as the argument to the thread and updater
_queue = queue.Queue()
# create and start a thread
thread = threading.Thread(target=ask_input, args=(_queue,))
thread.start()
# start updating the label
update_label(_queue, thread)
# check if the code is run without importing
if __name__ == '__main__':
root = tk.Tk()
# set this attribute so that the window always stays on top
# so that you can immediately see the changes in the label
root.attributes('-topmost', True)
# create the event
event = threading.Event()
# if window is destroyed set event which will break the loop
root.bind('<Destroy>', lambda _: event.set())
label = tk.Label(root)
label.pack()
start_thread()
root.mainloop()
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
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()
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()
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()