从线程调用def

时间:2013-09-26 18:25:59

标签: python-3.x python-multithreading

是否有人知道如何将def形式称为线程。

时钟节目:

import sys
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
from time import sleep
import threading

class MyThread ( threading.Thread ):
    def mclock(): # function that it can't call
        x = 1
        z = 0
        while x != -1:
            Label(mGui,text = str(x) + "second(s)").pack()
            x = x+1
            sleep(1)
            if x == 60:
                x = 1
                z = z+1
            Label(mGui, text= str(z) + " minute(s) has past.").pack()
            return
        return

MyThread().start()

mGui = Tk()

mGui.geometry("300x200+100+100")
mGui.title("Jono's Clock")

menubar = Menu(mGui)

filemenu = Menu(menubar, tearoff = 0)
filemenu.add_command(label = "Clock",command = mclock) # can't use function

menubar.add_cascade(label = "File",menu = filemenu)
mGui.config(menu = menubar)

mGui.mainloop()

如果有人发现任何其他错误,请说明。我也在使用Windows 7和python 3.3。

1 个答案:

答案 0 :(得分:1)

您发布的代码中存在多个语法错误,我不确定您对它们的确切意图,因此这里概述了如何从线程运行内容。

如果您希望线程从自定义线程类运行您自己的代码,通常的方法是将代码放在名为run的方法中,该方法将在线程启动时自动执行:

import threading

class MyThread(threading.Thread):
    def run(self):
        # do your stuff here
        print("Hello World")

MyThread().start()

或者,如果您不需要类,可以在模块的顶层创建函数,并将其作为参数传递给threading.Thread的构造函数:

def my_function():
    print("Hello World")

threading.Thread(target=my_function).start()

请注意,您经常希望保留对线程对象的引用,而不是像上面的代码那样让它继续。这需要您使用两行来创建然后启动线程:

thread = MyThread() # or the alternative version
thread.start()

这可以让你以后做:

thread.join()

确保线程完成其工作。

相关问题