Foros del Web » Programando para Internet » Python »

Timer en Python

Estas en el tema de Timer en Python en el foro de Python en Foros del Web. Buenas tardes, desde hace tres dias ando trabajando en una cuenta regresiva en python, todo iva bien hasta que fue necesario implementar un timer. Mi ...
  #1 (permalink)  
Antiguo 17/05/2012, 15:11
 
Fecha de Ingreso: mayo-2011
Mensajes: 4
Antigüedad: 12 años, 11 meses
Puntos: 1
Timer en Python

Buenas tardes, desde hace tres dias ando trabajando en una cuenta regresiva en python, todo iva bien hasta que fue necesario implementar un timer.

Mi codigo es este:

Código:
from Tkinter import *
import customTimerNew
from threading import * 

_t = None

def startPomodoro(pomodoro):
		_t = Timer(1, pomodoro.discountTime())
		#_t.start()

class Pomodoro:
	_form = None
	_master = None
	_reloj = None
	_timeLabel = "25:00"
	_timeout = 1

	def __init__(self):
		self.startApp(self._master)

	def startApp(self, master):
		self._form = Frame(master)
		self._form.pack()

		title = Label(self._form, text="Pomodoro by Xogost!")

		self._reloj = Label(self._form, text=self._timeLabel)

		startButton = Button(self._form, text="Iniciar Pomodoro", command=startPomodoro(self))

		title.pack()
		self._reloj.pack()
		startButton.pack()
		self._form.mainloop()

	def discountTime(self):
		runtime = self._timeLabel.split(':')
		if runtime[1] == "00":
			runtime[0] = int(runtime[0]) - 1
			runtime[1] = 59
		elif int(runtime[0]) == 0 and int(runtime[1]) == 0:
			self._timeout = 0
		else:
			runtime[1] = int(runtime[1]) - 1

		if int(runtime[1]) < 10 and int(runtime[0]) < 10:
			self._timeLabel = "0%d:0%d" % (int(runtime[0]), int(runtime[1]))
		elif int(runtime[1]) < 10:
			self._timeLabel = "%d:0%d" % (int(runtime[0]), int(runtime[1]))
		elif int(runtime[0]) < 10:
			self._timeLabel = "0%d:%d" % (int(runtime[0]), int(runtime[1]))
		else:
			self._timeLabel = "%d:%d" % (int(runtime[0]), int(runtime[1]))
		
		self._reloj.config(text=self._timeLabel)
		self._reloj.update_idletasks()
y el error es este:

Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib64/python2.7/lib-tk/Tkinter.py", line 1410, in _call_
return self.func(*args)
File "main.py", line 55, in startPomodoro
self._t.run()
File "/home/xogost/Documentos/Python/Pomodoro/customTimer.py", line 13, in run
self.handler()
TypeError: 'NoneType' object is not callable

Les agradezco si me pueden colaborar.
  #2 (permalink)  
Antiguo 18/05/2012, 09:14
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Timer en Python

En tu modulo customTimer.py, checa self.handler es None a la hora de la llamada.
  #3 (permalink)  
Antiguo 18/05/2012, 10:02
 
Fecha de Ingreso: mayo-2011
Mensajes: 4
Antigüedad: 12 años, 11 meses
Puntos: 1
Respuesta: Timer en Python

El modulo customTimer.py es una clase de ayuda que encontre en la web ya que no encontraba respuesta alguna asi que este es el codigo:

Código Python:
Ver original
  1. import threading
  2. import time
  3.  
  4. TIMER_ON_TIME = 1
  5.  
  6. class ResettableTimer(threading.Thread):
  7.   """
  8.  The ResettableTimer class is a timer whose counting loop can be reset
  9.  arbitrarily. Its duration is configurable. Commands can be specified
  10.  for both expiration and update. Its update resolution can also be
  11.  specified. Resettable timer keeps counting until the "run" method
  12.  is explicitly killed with the "kill" method.
  13.  """
  14.   def __init__(self, maxtime, expire, inc=None, update=None):
  15.     """
  16.    @param maxtime: time in seconds before expiration after resetting
  17.                    in seconds
  18.    @param expire: function called when timer expires
  19.    @param inc: amount by which timer increments before
  20.                updating in seconds, default is maxtime/2
  21.    @param update: function called when timer updates
  22.    """
  23.     self.maxtime = maxtime
  24.     self.expire = expire
  25.     if inc:
  26.       self.inc = inc
  27.     else:
  28.       self.inc = maxtime/2
  29.     if update:
  30.       self.update = update
  31.     else:
  32.       self.update = lambda c : None
  33.     self.counter = 0
  34.     self.active = True
  35.     self.stop = False
  36.     threading.Thread.__init__(self)
  37.     self.setDaemon(True)
  38.   def set_counter(self, t):
  39.     """
  40.    Set self.counter to t.
  41.  
  42.    @param t: new counter value
  43.    """
  44.     self.counter = t
  45.   def deactivate(self):
  46.     """
  47.    Set self.active to False.
  48.    """
  49.     self.active = False
  50.   def kill(self):
  51.     """
  52.    Will stop the counting loop before next update.
  53.    """
  54.     self.stop = True
  55.   def reset(self):
  56.     """
  57.    Fully rewinds the timer and makes the timer active, such that
  58.    the expire and update commands will be called when appropriate.
  59.    """
  60.     self.counter = 0
  61.     self.active = True
  62.  
  63.   def run(self):
  64.     """
  65.    Run the timer loop.
  66.    """
  67.     while True:
  68.       self.counter = 0
  69.       while self.counter < self.maxtime:
  70.         self.counter += self.inc
  71.         time.sleep(self.inc)
  72.         if self.stop:
  73.           return
  74.         if self.active:
  75.           self.update(self.counter)
  76.       if self.active:
  77.         self.active = False
  78.         self.expire()
  79.  
  80. class Relay:
  81.   def __init__(self, id):
  82.     self.id = id
  83.  
  84.     print '** Starting ' + str(id) + ' ON for ' + str(TIMER_ON_TIME) + ' seconds'
  85.  
  86.     self.timer = ResettableTimer(TIMER_ON_TIME, self.process_event)
  87.     self.timer.start()
  88.  
  89.   # handle the relay switching on timer event
  90.   def process_event(self):
  91.  
  92.     # execute some logic
  93.     # ...
  94.     # ...
  95.  
  96.     print 'Inside event for Relay: ', str(self.id)
  97.  
  98.     # reset the timer
  99.     self.timer.maxtime = TIMER_ON_TIME
  100.  
  101.     # restart the timer
  102.     print '@ Restarting timer: ', str(self.id)
  103.     self.timer.reset()
  104.  
  105. ########### MAIN ###########
  106.  
  107. # create 3 timer objects
  108. relays = []
  109. for i in range( 3 ):
  110.  
  111.   relays.append( Relay( i ) )
  112.  
  113. # Main loop
  114. while True:
  115.   time.sleep( 10 )  # sleep until it's time to do something in this loop
  116.   print '>> active threads: ', threading.activeCount(), '\n'  # this might need to be active_count()
  117.                                                                               # depending on your python version

Última edición por razpeitia; 18/05/2012 a las 23:23 Razón: Syntax Highlight!!!!
  #4 (permalink)  
Antiguo 18/05/2012, 20:09
 
Fecha de Ingreso: marzo-2010
Ubicación: Mérida, Venezula
Mensajes: 73
Antigüedad: 14 años
Puntos: 0
Respuesta: Timer en Python

Serias tan amable de arreglar la identación, así es imposible leerlo.
  #5 (permalink)  
Antiguo 18/05/2012, 23:26
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Timer en Python

Mi pregunta es ¿por que no hiciste simplemente usaste el timer de tkinter?

http://stackoverflow.com/questions/2...gui-in-tkinter
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 13:07.