Thursday, July 10, 2008

Showing a webcam image in the desktop window using Python. Part 3: self-refreshing app

This is the last part of a three-part series. In the first part, I've described how to read image from the web. The second part was dedicated to showing images in a window on the desktop. This last part will deal with auto-refreshing of the displayed image. This is particularly useful when you want to display a webcam image which is regularly updated.
To handle autorefresh we will use a Tkinter method after() which will call a defined function after some given delay.
To the previous code, we will add the following function:


def timingloop(start=0):
now = time.clock()
if start == 1:
getimagefromweb(myurl)
if now > container.start + container.refresh:
getimagefromweb(myurl)
container.start = now
else:
remains = str(int(container.refresh - now + container.start))
message = 'Next update in '+remains+' seconds.'
container.statusbarVar.set(message)
container.statusbar.update()
container.main.after(200, timingloop)

This function controls downloading new images by calling getimagefromweb() and checks when to do it by comparing saved times with current time. Finally, the function calls itself after 200 miliseconds.
For the program to work you also have to add some other stuff into the code. To the beginning add "import time" to import time library. The last part of the script has to be slightly modified as follows:


# the script
myurl = 'http://siemens.mesto-zatec.cz/obrazek.jpg'
container = Container()
container.width = 800
container.height = 602

container.start = time.clock()
container.refresh = 20 # window refresh rate in seconds

drawwindow()
timingloop(1)

mainloop()
print 'end OK'

We have added two new variables with timestamp and a refresh rate in seconds after which the image will be re-loaded. Finally, the getimagefromweb() function has been replaced by the timingloop() with parameter "1" which tells it that it is the start of the program and that it should load the image immediately. After the first timingloop() there is enough time to call mainloop() without which the program hangs (and I'm not sure why). As you can see using after() is a bit unintuitive because you can call other functions after "after()" was called and is still running in the background.

1 comment:

Andry Andry said...

First of all congratulations for your support, just as enlightening and asked. That said, some details could include more details such as towards the conclusion. It's just a way to say I'm eager to read more.