简体   繁体   English

来自另一个类的Tkinter多处理和调用函数

[英]Tkinter multiprocessing and calling functions from another class

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. 我有一个问题,我想在ThreadedTask类中调用random_task()函数,但不确定如何执行此操作。 I am using Python 2.7 if that makes a difference. 我正在使用Python 2.7,如果有所作为。 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()

All you need to do is to extend ThreadedTask like so: 您需要做的就是像这样扩展ThreadedTask

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 ): 然后这样调用它(来自TestClass ):

ThreadedTask(self, self.queue).start()

However, in the code you gave, process() is never called. 但是,在您提供的代码中,永远不会调用process() Doing so will also call random_task() from the ThreadedTask class. 这样做还将从ThreadedTask类调用random_task()

This, by the way, can be applied to almost every class in Python when needed. 顺便说一下,这可以在需要时应用于几乎Python中的每个类。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM