Reputation: 45
I have a problem where I would like to call the random_task()
function in the ThreadedTask class and wasn't sure how to go about doing this. I am using Python 2.7 if that makes a difference. I would also like to be able to run it inside some sort of loop which would repeat until the application is closed but I will ask that in a different question.
import Tkinter as tk
import os, Queue, threading, time
class TestClass(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.create_view()
def create_view(self):
self.labelTitle = tk.Label(self, text="page",)
self.labelTitle.pack()
def random_task(self):
print("test")
def process(self):
self.queue = Queue.Queue()
ThreadedTask(self.queue).start()
self.master.after(100, self.process_queue)
def process_queue(self):
try:
msg = self.queue.get(0)
except Queue.Empty:
self.master.after(100, self.process_queue)
class ThreadedTask(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
#I want to run random_task() here
time.sleep(5)
self.queue.put("Task finished")
app = TestClass()
app.geometry("800x600")
app.mainloop()
Upvotes: 0
Views: 292
Reputation: 6429
All you need to do is to extend ThreadedTask
like so:
class ThreadedTask(threading.Thread):
def __init__(self, parent, queue):
threading.Thread.__init__(self)
self.parent = parent
self.queue = queue
def run(self):
self.parent.random_task()
time.sleep(5)
self.queue.put("Task finished")
And then call it like so (from the TestClass
):
ThreadedTask(self, self.queue).start()
However, in the code you gave, process()
is never called. Doing so will also call random_task()
from the ThreadedTask
class.
This, by the way, can be applied to almost every class in Python when needed.
Hope this helps!
Upvotes: 1