manuelBetancurt
manuelBetancurt

Reputation: 16128

python thread using start_new_thread not working

Im in need of a thread for my python app,

in my test i have a counter with a timer simulating the loop i need to run, but the problem is that this loop calls fine from a basic python sample on the thread, but not working on my code, I must be calling the method wrong?

here my code [with the problem]

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()

And here the sample working code with thread

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

thanks

Upvotes: 0

Views: 11219

Answers (1)

Karmastan
Karmastan

Reputation: 5696

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

NameError: global name 'print_time' is not defined

I'm guessing that you meant self.print_time, the class method, instead of print_time, the global name that happens to be undefined.

Upvotes: 3

Related Questions