generating Another thread in Python - python

Newbie to Python, Basically I have a window UI with few buttons, when I push one button, I would like to start processing/parsing files in background while I can still play with the UI, however my UI becomes unresponsive "spinning wheel".
class MyUI(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background="white")
self.parent = parent
self.initUI()
def initUI(self):
self.validate_button = Button(self,
text='Validate',
command=self.validate_files).pack()
def validate_files(self):
try:
t = Thread(target=self.process_files(), args=('labala',1))
t.start
t.join
except Exception, errtxt:
print errtxt
def process_colls(self):
items = self.lb.curselection()
for i in items:
self.do_parse(self.varDirName, self.lb.get(int(i)))
def main():
root = Tk()
root.geometry("600x600+300+300")
app = MyUI(root)
root.mainloop()
if __name__=="__main__":
main()

Replace self.process_files() with self.process_files where you create the thread:
t = Thread(target=self.process_files, args=('labala',1))
You should pass a fuction to thread as target and not a result.
Moreover don't use join() if you want that the function return while the thread is running.

try starting a thread using threading.Thread. This snippet should help you find more answers
from threading import Thread
...
_thread = Thread(target=lambda: my_func())
_thread.start()
In your example you forgot the parentheses to call methods.

Related

How to give a daemon thread a stop event

I am trying to get my head around threading in python, I have pieced together a simple tkinter UI that can run a background task to better understand how it all works.
I seem to have got to the point where I can create a seperate thread and interact with the GUI but the problem comes when I try to carry out the task the second time.
I believe what I am missing is a way to tell the daemon when to stop the thread.
Here is my code thus far:
import threading
import tkinter as tk
from collections import deque
from threading import Thread
from random import randint
from time import sleep
class Emitter:
def __init__(self):
self.stop_event = threading.Event()
self.thread = Thread(target=self.emit_text)
self.running = False
def emit_text(self):
sleep(3)
messageQueue.append(f'Random number: {randint(0, 100)}')
# self.thread.set()
def start_emit(self):
ui.consume_text()
self.thread.setDaemon(True)
self.thread.start()
class UI:
def __init__(self):
self.root = tk.Tk()
self.label = tk.Label(self.root, text='Original text')
self.label.pack()
start = tk.Button(self.root, text='Start Download', command=lambda x=Emitter(): x.start_emit())
start.pack()
def consume_text(self):
try:
self.label['text'] = messageQueue.popleft()
except IndexError:
self.root.after(ms=1000, func=self.consume_text)
messageQueue = deque()
ui = UI()
ui.root.mainloop()
I have tried to understand other answers but I can't grasp how you tell the daemon/thread what it's condition to stop is.
The prgram works as intended the first time you click the button, but then if you try to click it again it gives the error RuntimeError: cannot set daemon status of active thread even if I have waited for the Emitter to finish it's task
Thanks to #Solomon Slow for their comment, the problem I had was I was trying to restart the thread but in fact I should have been creating a new one each time.
To fix the problem, I changed my class Emitter class to create a new thread each time start_emit() is called.
The fixed class:
class Emitter:
def __init__(self):
self.stop_event = threading.Event()
def emit_text(self):
sleep(3)
messageQueue.append(f'Random number: {randint(0, 100)}')
def start_emit(self):
ui.consume_text()
thread = Thread(target=self.emit_text)
thread.start()
I also removed the self.thread.setDaemon(True) line.

Destroy Tkinter window in thread

I have a project where a passive GUI runs in its own thread and is manipulated by the main thread. Especially, the window is closed by the main thread using event_generate:
from tkinter import Tk
import threading
import time
import queue
q = queue.Queue()
class Window:
def __init__(self):
self.root = Tk()
self.root.title("test")
self.root.bind("<<custom_close_event>>", self.close)
def close(self, event):
print("quit")
self.root.destroy()
def create_window():
window = Window()
q.put(window)
window.root.mainloop()
print("###########")
# Window creation executed in different thread
t1 = threading.Thread(target=create_window)
t1.start()
window = q.get()
time.sleep(2)
window.root.event_generate("<<custom_close_event>>")
print("end")
The program crashes with the following output:
quit
###########
Tcl_AsyncDelete: async handler deleted by the wrong thread
[1] 21572 IOT instruction (core dumped) python window_test.py
According to this discussion, it seems that the order of objects cleanup in multithreaded environment is in fault. The advice to nullify objects (in my case window) and to call gc.collect did not solve the problem.
How should I do?
Instead of using a separate thread to create a second reference to Tk(),
Just inherit tk.Toplevel when you create the "Window" class.
This will allow you to have really as many windows as you want.
You can use tk.after in order to monitor processes and do pseudo-multithreading things. Here's an example of how to do that
class Window(Toplevel):
def __init__(self, parent, *args, **kwargs):
super().__init__(*args, **kwargs)
self.parent = parent
...
self.parent.after(1000, self.do_something)
def do_something(self):
...
<code>
...
self.parent.after(1000, self.do_something)
root = Tk()
Window(root)
root.mainloop()
Using #AndrewPye's answer but inheriting from Tk instead of Toplevel:
from tkinter import *
class Window(Tk):
def __init__(self, **kwargs):
super().__init__(**kwargs)
super().after(1000, self.do_something)
def do_something(self):
print("I am in a loop that runs every 1000ms = 1s")
super().after(1000, self.do_something)
root = Window()
root.mainloop()

Thread won't stop until window is destroyed, window won't destroy unless thread is stopped

So I have a window which is controlled by a thread that runs in the background and changes the GUI when necessary, at some point this thread will be instructed to change window (involving destroying the window it is in and starting up another window), but this never happens because the thread won't stop executing until the window is changed.
Below is a simplified example:
class Window1:
def __init__(...):
self.Master = tk.Tk()
# some code
self.BackgroundUpdates = threading.Thread(target=self.ActiveWindow)
self.BackgroundUpdates.start()
def ActiveWindow(self):
# gets some instruction
if instruction == 'next window':
nextWindow(self)
def StartWindow(self):
self.Master.mainloop()
def KillWindow(self):
self.Master.destroy()
class Window2:
def __init__(...):
self.Master = tk.Tk()
# some code...
def StartWindow(self):
self.Master.mainloop()
def nextWindow(objectWindow):
objectWindow.KillWindow()
# when this function is called it never gets past the line above
nextWindow = Window2()
nextWindow.StartWindow()
application = Window1()
application.StartWindow()
Is there a way that I could rearrange the way I handle the thread so that I don't run into this problem?
a runnable example:
import tkinter as tk
import threading
class MainWindow:
def __init__(self):
self.Master = tk.Tk()
self.Frame = tk.Frame(self.Master, width=100, height=100)
self.Frame.pack()
self.Updates = threading.Thread(target=self.BackgroundUpdates)
self.Updates.start()
def BackgroundUpdates(self):
# imagine instructions to be a really long list with each element being a
# different instruction
instructions = ['instruction1', 'instruction2', 'next window']
while True:
if instructions[0] == 'next window':
ChangeWindow(self)
else:
instructions.remove(instructions[0])
def StartWindow(self):
self.Master.mainloop()
def KillWindow(self):
self.Master.destroy()
class SecondaryWindow:
def __init__(self):
self.Master = tk.Tk()
self.Frame = tk.Frame(self.Master, width=100, height=100)
self.Frame.pack()
def StartWindow(self):
self.Master.mainloop()
def KillWindow(self):
self.Master.destroy()
def ChangeWindow(oldObject):
oldObject.KillWindow()
# the line above will halt the program, since it has to wait on the thread to
# finish before the window can be destroyed, but this function is being called
# from within the thread and so the thread will never stop executing
del oldObject
newObject = SecondaryWindow()
newObject.StartWindow()
window = MainWindow()
window.StartWindow()
I realised that tkinter is singularly threaded, it can be explained more here:
https://stackoverflow.com/a/45803955/11702354
The problem was that I was trying to destroy my window from a different thread to the one it was created in. To solve this problem I had to use the 'after' method from the Tkinter module as well as using a event, this meant that I could control the background stuff (i.e. wait on a specific command from my connected server) and when I needed to change the window I would set the event.
Part of my adapted code can be seen below:
def CheckEvent(self):
if LOBBY_EVENT.is_set():
ChangeWindow(self, 'game')
self.Master.after(5000, self.CheckEvent)
def StartWindow(self):
self.Master.after(5000, self.CheckEvent)
self.Master.after(2000, self.HandleInstruction)
self.Master.mainloop()
So whenever I was calling the StartWindow method for my window, it would check whether the event has been set every 5 seconds, and then every 2 seconds it would go to a separate function 'HandleInstruction' which allowed me to create a response in my GUI (I also used queues to pass information to this function)
I hope this clears up confusion if anyone is to stumble across it!

Passing variables into a tkinter class window

I want to create a GUI in tkinter that not only executes commands when a button is pressed, but responds to the state of a larger script running in a separate thread.
I have really dug around and tried to find some information on message passing, and I have found some great info on the pickle module, using multiprocessing and its built in tools and also threading, and queuing. I have even dug into David Beazley's lesson on concurrency located here. I just can't get the syntax right on any of those methods.
I have broken down my code into a small functional unit that should launch a little tkinter window like this:
tkinter window
The code below has a "launchGUI" function that launches my tkinter GUI, a "myLoop" function that starts the threads and will also loop to drive my larger program later, right now it just rotates the blink variable. I also have a blinkCheck method in my class that checks the status of the blink variable in the class.
I don't know if I am even putting my message receiver in the right place. In the following example code I am just trying to pass a global variable into the class. I know it is getting into the class, because the blinkCheck() method works even though uncommenting that method crashes the window. However, with the method turned off the label in the GUI never changes. I think the window crashing is the least of my worries, it must be because i have another while loop running.
What is the correct way to get that number in Label to change?
Here is my example code:
import tkinter as tk
from tkinter import Frame, Label
import time
import threading
blink = 0
class MyClass(tk.Frame):
def __init__(self, master):
self.master = master
super().__init__(self.master)
global blink
self.label = Label(master, text=blink)
self.label.pack()
#self.blinkCheck()
def blinkCheck(self):
global blink
while True:
print("blink in blinkCheck method is = {}".format(blink))
time.sleep(2.5)
def launchGUI():
root = tk.Tk()
root.title("My Blinker")
app1 = MyClass(root)
app1.mainloop()
def myLoop():
global blink
t1=threading.Thread(target=launchGUI)
t1.daemon = True
t1.start()
print("blink in blinker function is {}".format(blink))
while True:
if blink == 0:
blink = 1
else:
if blink == 1:
blink = 0
time.sleep(2.5)
if __name__=="__main__":
myLoop()
In your description you have mentioned something about involving buttons. I do not see that in your provided snippet. But with buttons it is possible to configure the label, i.e:
from tkinter import Label, Button
blink = 0
class MyClass(tk.Frame):
def __init__(self, master):
self.master = master
super().__init__(self.master)
global blink
self.label = Label(master, text=blink)
self.button = Button(master, text="Button", command=lambda: foo(self.label))
self.label.pack()
self.button.pack()
#self.blinkCheck()
def blinkCheck(self):
global blink
while True:
print("blink in blinkCheck method is = {}".format(blink))
time.sleep(2.5)
def foo(self, label):
label.config(text=blink)
Conventionally, this would be the most simple way to configure a label within an active thread.
If anyone feels like this answer may not be fully correct, please do edit it because I am new to Stack Overflow!
First, the GUI must run in main thread, and must not blocked by a infinite loop. Use after instead. To communicate, use some appropriate object from threading, e.g. Event:
import tkinter as tk
import time
import threading
class MyClass(tk.Frame):
def __init__(self, master, event):
super().__init__(master)
self.master = master
self.event = event
self.label = tk.Label(master, text='')
self.label.pack()
self.after(100, self.blink_check)
def blink_check(self):
self.label['text'] = self.event.is_set()
self.after(100, self.blink_check)
def blink(event):
while True:
event.set()
time.sleep(2.5)
event.clear()
time.sleep(2.5)
def main():
root = tk.Tk()
root.title("My Blinker")
event = threading.Event()
t = threading.Thread(target=blink, args=(event,))
t.daemon = True
t.start()
frame = MyClass(root, event)
root.mainloop()
if __name__=="__main__":
main()

Python Threading

I'm trying to make a simple program that continually displays and updates a label that displays the CPU usage, while having other unrelated things going on.
I've done enough research to know that threading is likely going to be involved. However, I'm having trouble applying what I've seen in simple examples of threading to what I'm trying to do.
What I currently have going:
import Tkinter
import psutil,time
from PIL import Image, ImageTk
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.labelVariable = Tkinter.StringVar()
self.label = Tkinter.Label(self,textvariable=self.labelVariable)
self.label.pack()
self.button = Tkinter.Button(self,text='button',command=self.A)
self.button.pack()
def A (self):
G = str(round(psutil.cpu_percent(), 1)) + '%'
print G
self.labelVariable.set(G)
def B (self):
print "hello"
if __name__ == "__main__":
app = simpleapp_tk(None)
app.mainloop()
In the above code I'm basically trying to get command A continually running, while allowing command B to be done when the users presses the button.
You should never attempt to alter a UI element from a thread that isn't the main thread.
What you probably want is after(delay_ms, callback, args). Some information can be over at http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm.
As a sample, here's a quick script to show a clock (Note: I've never really used Tk).
from Tkinter import *
from time import strftime
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.label_var = StringVar()
self.label = Label(self, textvariable=self.label_var)
self.label.pack()
# Start the loop
self.go()
def go(self):
self.label_var.set(strftime("%H:%M:%S"))
# The callback is only called once, so call it every time
self.after(1000, self.go)
app = App()
mainloop()
You don't need threads for such a simple task. You can simply schedule your task to run every second or so, which can be done with the 'after' method;
First, add this method to your simpleapp_tk class:
def update(self):
G = str(round(psutil.cpu_percent(), 1)) + '%'
self.labelVariable.set(G)
self.after(1000, self.update)
Then, in your initialize method add this call:
self.update()
This will cause the label to be updated to the current cpu value. The update method will then re-schedule itself to run again in one second.

Categories