使用start_new_thread的python线程不起作用

时间:2013-12-03 00:13:21

标签: multithreading python-2.7

我需要一个用于我的python应用程序的线程,

在我的测试中我有一个计时器模拟我需要运行的循环计数器,但问题是这个循环从线程上的基本python样本调用很好,但不能处理我的代码,我必须调用方法错了吗?

这里是我的代码[有问题]

import thread  
import threading
from threading import Thread
import time

from Tkinter import *
from Tkinter import Tk

import sys

root = Tk()
mainframe = Frame(root) #  mainframe contained by root!, init

class myclass():

    def __init__(self):
        self.main() #atencion! es un loop! se quedara aqui!
        # en objC [self main]

    def submitForm(self,*args):
        print "submitalo"
        thread.start_new_thread( print_time, ("Thread-2", 4, ))


    def print_time( threadName, delay):
        count = 0
        while count < 5:
            time.sleep(delay)
            count += 1
            print "%s: %s" % ( threadName, time.ctime(time.time()) )

    def main(self): 
        print("from main")
        mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) #  add subview mainframe
        mainframe.columnconfigure(0, weight=1)
        mainframe.rowconfigure(0, weight=1)
        button = Button(mainframe, text='Submit', command=self.submitForm)
        button.grid(column=1 , row=3, sticky=(W,E))  

    #my loop
        root.mainloop()

if __name__ == "__main__":
    myclass()

这里是带有线程的示例工作代码

import thread
import time

# Define a function for the thread
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print "%s: %s" % ( threadName, time.ctime(time.time()) )

# Create two threads as follows
try:
   thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print "Error: unable to start thread"

while 1:
   pass

感谢

1 个答案:

答案 0 :(得分:2)

        thread.start_new_thread( print_time, ("Thread-2", 4, ))
  

NameError:未定义全局名称'print_time'

我猜你的意思是self.print_time,类方法,而不是print_time,这个全局名称恰好是未定义的。