Displaying and refreshing my picture every 5 seconds - python

Ok, I've got the GUI in tkinter working, and I'm trying to grab and image every 5 seconds and display it in a Label named Picturelabel.
from Tkinter import *
from PIL import ImageGrab
import cStringIO, base64, time, threading
class PictureThread(threading.Thread):
def run(self):
print "test"
box = (0,0,500,500) #x,x,width,height
MyImage = ImageGrab.grab(box)
fp = cStringIO.StringIO()
MyImage.save(fp, 'GIF')
MyPhotoImage = PhotoImage(data=base64.encodestring(fp.getvalue()))
time.sleep(5)
PictureThread().run() #If I get rid of this then it just display one image
return MyPhotoImage
MyVeryNewImage = PictureThread().run()
Picturelabel = Label(BalanceFrame, image=MyVeryNewImage)
Picturelabel.grid(row=3, column=2, columnspan=3)
Picturelabel.image = MyVeryNewImage
window.mainloop()
Firstly how can I clean up this code, as starting a thread inside another thread can't be good practice.
Also when I run this it prints "test" in the console, but it does not bring up the GUI.
If I comment out the commented text (PictureThread().run() where I'm creating yet another thread inside it.) then it displays the first image, but not any more.

You should call start() instead of run(). From the Documentation:
Once a thread object is created, its
activity must be started by calling
the thread’s start() method. This
invokes the run() method in a separate
thread of control.
I see you're invoking a new thread inside your run() method. This will cause you to spawn infinite threads!
EDIT: I'm not sure if this works:
from Tkinter import *
from PIL import ImageGrab
import cStringIO, base64, time, threading
Picturelabel = Label(BalanceFrame)
Picturelabel.grid(row=3, column=2, columnspan=3)
class PictureThread(threading.Thread):
def run(self):
print "test"
box = (0,0,500,500) #x,x,width,height
fp = cStringIO.StringIO()
while(1):
MyImage = ImageGrab.grab(box)
MyImage.save(fp, 'GIF')
self.image = PhotoImage(data=base64.encodestring(fp.getvalue()))
Picturelabel.image = self.image
fp.reset() # reset the fp position to the start
fp.truncate() # and truncate the file so we don't get garbage
time.sleep(5)
PictureThread().start()
window.mainloop()

The problem is that you return the new image from the PictureThread().run() in the method, but you never save it.
How about:
from Tkinter import *
from PIL import ImageGrab
import cStringIO, base64, time, threading
box = (0,0,500,500) #x,x,width,height
MyImage = ImageGrab.grab(box)
fp = cStringIO.StringIO()
MyImage.save(fp, 'GIF')
MyPhotoImage = PhotoImage(data=base64.encodestring(fp.getvalue()))
Picturelabel = Label(BalanceFrame, image=MyPhotoImage)
Picturelabel.grid(row=3, column=2, columnspan=3)
class PictureThread(threading.Thread):
def run(self):
while True:
box = (0,0,500,500) #x,x,width,height
MyImage = ImageGrab.grab(box)
fp = cStringIO.StringIO()
MyImage.save(fp, 'GIF')
MyPhotoImage = PhotoImage(data=base64.encodestring(fp.getvalue()))
time.sleep(5)
Picturelabel.image = MyPhotoImage
PictureThread().start()
window.mainloop()

Related

Why does the multithread function not run before the timer?

I am trying to use multithreading to show a loading wheel while doing some background calculations.
I try to start the multithreaded function, and then run a timer to simulate the calculations.
The problem is the thread first starts running when the timer is over, even though I am starting the thread first...
from tkinter import *
from tkinter import messagebox
import time
from threading import *
from PIL import Image, ImageTk
# Create Object
root = Tk()
# Set geometry
root.geometry("400x400")
flag = True
# use threading
def threading():
t1=Thread(target=work)
t1.start()
time.sleep(10)
# work function
def work():
print("sleep time start")
image = Image.open("Static/spinner0.png")
img = ImageTk.PhotoImage(image)
lab = Label(root,image=img)
lab.pack()
while flag:
for i in range(8):
image = Image.open("Static/spinner"+str(i)+".png")
img = ImageTk.PhotoImage(image)
lab['image'] = img
time.sleep(0.2)
#return False
print("sleep time stop")
def on_closing():
if messagebox.askokcancel("Quit", "Do you want to quit?"):
flag = False
root.destroy()
# Create Button
Button(root,text="Click Me",command = threading).pack()
# Execute Tkinter
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
Just putting the answer here to avoid people digging comments for the solution.
One way to do this is to have both the calculations and the updating function running on extra different threads, this way the main process event loop stays uninterrupted and you get to call time.sleep, which is fine so long as it doesn't happen in your main thread.
A thread in python consumes below 100KB of memory (plus memory for variables in code running on it), so it's fine to have multiple threads running.
from tkinter import *
from tkinter import messagebox
import time
from threading import *
from PIL import Image, ImageTk
# Create Object
root = Tk()
# Set geometry
root.geometry("400x400")
flag = True
# use threading
def threading():
t1 = Thread(target=work)
t1.start()
t2 = Thread(target=time.sleep,args=(10,)) # the heavy computation function.
t2.start()
# control is given back to the main event loop
# work function
def work():
print("sleep time start")
image = Image.open("Static/spinner0.png")
img = ImageTk.PhotoImage(image)
lab = Label(root,image=img)
lab.pack()
while flag:
for i in range(8):
image = Image.open("Static/spinner"+str(i)+".png")
img = ImageTk.PhotoImage(image)
lab['image'] = img
time.sleep(0.2)
#return False
print("sleep time stop")
def on_closing():
if messagebox.askokcancel("Quit", "Do you want to quit?"):
flag = False
root.destroy()
# Create Button
Button(root, text="Click Me", command=threading).pack()
# Execute Tkinter
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()

Slide show program, event processing

I need the images to change if the cursor is inside the window without moving, but I managed to make the image changes only if the cursor is moving inside the window, how can I change the code?
from itertools import cycle
import tkinter as tk
from PIL import ImageTk, Image
import glob
image_files = glob.glob("*.jpg")
root = tk.Toplevel()
root.geometry("1600x900")
pictures = cycle((ImageTk.PhotoImage(file=image), image) for image in image_files)
picture_display = tk.Label(root)
picture_display.pack()
def show_slides(event):
img_object, img_name = next(pictures)
root.after(500, picture_display.config(image=img_object))
root.bind("<Motion>", show_slides)
root.mainloop()
You could bind the <Enter> and <Leave> events and use a flag to control the call, followed by using the after method to loop the function.
def show_slides(event=None):
global change_slide
img_object, img_name = next(pictures)
picture_display.config(image=img_object)
change_slide=root.after(500,show_slides)
def stop_slides(event):
root.after_cancel(change_slide)
root.bind("<Enter>", show_slides)
root.bind("<Leave>", stop_slides)
UPDATE
Using a flag might cause multiple calls being scheduled it the events happen during the 500ms delay, you can use after_cancel to terminate it.
You can calculate cursor position in loop and show image if it's located within tkinter window:
import glob
import tkinter as tk
from PIL import ImageTk
from itertools import cycle
class App(object):
def __init__(self):
self.root = tk.Tk()
self.root.geometry('900x600')
self.lbl = tk.Label(self.root)
self.lbl.pack()
files = glob.glob('*.jpg')
self.images = cycle((ImageTk.PhotoImage(file=f), f) for f in files)
self.show()
self.root.mainloop()
def show(self):
abs_coord_x = self.root.winfo_pointerx() - self.root.winfo_rootx()
abs_coord_y = self.root.winfo_pointery() - self.root.winfo_rooty()
if 0 <= abs_coord_x <= self.root.winfo_width() and 0 <= abs_coord_y <= self.root.winfo_height():
img_object, img_name = next(self.images)
self.lbl.config(image=img_object)
self.root.after(1000, self.show)
App()

How to draw a circle on a label on Tkinter?

i tried to draw a circle (its supposed to be a mouse cursor) on a label that has an image in it.
the circle position needs to be changed every time i get it on the sockets
i noted the mouse poisition with ** on my code
i dont know how to do it, i will be glad if you help me,
thanks a lot
import socket
from PIL import Image
import StringIO
import Tkinter
from PIL import Image
from PIL import ImageTk
import threading
RECV_BLOCK=1024
s=socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.connect(("127.0.0.1",12345))
im = None
def ShowImage():
root = Tkinter.Tk()
label = Tkinter.Label(root)
label.pack()
img = None
tkimg = [None] # This, or something like it, is necessary because if you do not keep a reference to PhotoImage instances, they get garbage collected.
delay = 2 # in milliseconds
def loopCapture():
print "capturing"
# img = fetch_image(URL,USERNAME,PASSWORD)
global im
while im==None:
continue
img = im
tkimg[0] = ImageTk.PhotoImage(img)
label.config(image=tkimg[0])
root.update_idletasks()
root.after(delay, loopCapture)
loopCapture()
root.mainloop()
def rcvimage():
global im
for i in range(1000):
data=''
size=s.recv(RECV_BLOCK)
s.send(size)
size=int(size)
while True:
buf=s.recv(RECV_BLOCK)
data+=buf
if len(data)>=size:
break
pic =data[:data.find("$$$$$$")]
mouse=data[data.find("$$$$$$")+6:] # **the position of the cursor is here - for example ("125$200") - the first number is x, and the second is y**
print mouse
try:
print(len(pic))
f=StringIO.StringIO(pic)
global im
im=Image.open(f)
#ShowImage(im)
#im.show()
s.send ("next")
except Exception as e:
s.send("fail:"+e.message)
break
print "End"
thread2 = threading.Thread(target = rcvimage)
thread1 = threading.Thread(target = ShowImage)
thread1.start()
thread2.start()
You cannot draw an image on top of a label that already has an image. You can change the cursor itself with the configure method.
However, if you use a very small canvas rather than a label, you can draw on top of text that is added to the canvas.

Intermittent Python thread error, "main thread is not in main loop"

Middle aged dad (electrical engineer not programmer by trade) trying to teach my 13 year old daughter electronics and programming. So far, I love Python. I am building a program to display temperatures throughout our house with tkinter GUI and DS18B20 sensors.
We've pieced together the program below from reading books, online research and using Stack Overflow for trouble-shooting bugs (this site rocks!).
Now we're stumped, we keep getting an intermittent error, when we run the program the first time after loading idle on our Raspberry, it works fine.
The second time, and all subsequent times, we get this error message:
Traceback (most recent call last):
File "/home/pi/Code-working-library/stackoverflow-paste.py", line 140, in <module>
app.equipTemp.set(tempread)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 203, in set
return self._tk.globalsetvar(self._name, value)
RuntimeError: main thread is not in main loop
Note, our understanding is that in order to have a static window and update labels updated temps read off our sensor (DS18B20) we needed to use a thread. The sample code we started with has the _init_ statements with only one underscore preceding and trailing - not sure why, if I add a second underscore, I get error messages. The updating window code we used as our basis came from Raspberry Pi forum
Here is our code:
from Tkinter import *
import tkFont
import os
import glob
import time
import subprocess
import re
import sys
import time
import threading
import Image
import ImageTk
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
#28-000005c6ba08
sensors = ['28-000005c6ba08']
sensors1 = ['28-000005c70f69']
def read_temp_raw():
catdata = subprocess.Popen(['cat',device_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,err = catdata.communicate()
out_decode = out.decode('utf-8')
lines = out_decode.split('\n')
return lines
def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_f
########### build window ###################
bground="grey"
class App(threading.Thread):
def _init_(self):
threading.Thread._init_(self)
self.start()
def callback(self):
self.root.quit()
def run(self):
#Make the window
self.root = Tk()
self.root.wm_title("Home Management System")
self.root.minsize(1440,1000)
self.equipTemp = StringVar()
self.equipTemp1 = StringVar()
self.equipTemp2 = StringVar()
self.customFont = tkFont.Font(family="Helvetica", size=16)
# 1st floor Image
img = Image.open("HOUSE-PLANS-01.png")
photo = ImageTk.PhotoImage(img)
Label1=Label(self.root, image=photo)
Label1.place(x=100, y=100)
# 2nd floor
img2 = Image.open("HOUSE-PLANS-02.png")
photo2 = ImageTk.PhotoImage(img2)
Label1=Label(self.root, image=photo2)
Label1.place(x=600, y=100)
# Basement image
img3 = Image.open("HOUSE-PLANS-03.png")
photo3 = ImageTk.PhotoImage(img3)
Label1=Label(self.root, image=photo3)
Label1.place(x=100, y=500)
# Attic Image
img4 = Image.open("HOUSE-PLANS-04.png")
photo4 = ImageTk.PhotoImage(img4)
Label1=Label(self.root, image=photo4)
Label1.place(x=600, y=500)
# House Isometric Image
img5 = Image.open("house-iso.png")
photo5 = ImageTk.PhotoImage(img5)
Label1=Label(self.root, image=photo5)
Label1.place(x=1080, y=130)
#Garage Temp Label
Label2=Label(self.root, textvariable=self.equipTemp, width=6, justify=RIGHT, font=self.customFont)
Label2.place(x=315, y=265)
print "start monitoring and updating the GUI"
self.root.mainloop() #start monitoring and updating the GUI
########### Start Loop ###################
print "starting app"
app = App()
app.start()
print "app started"
################### Begin ds18b20 function ##############
while True:
# 28-000005c6ba08
i = "28-000005c6ba08"
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + i)[0]
device_file = device_folder + '/w1_slave'
tempread=round(read_temp(),1)
app.equipTemp.set(tempread)
time.sleep(5)
##################### END ds18b20 Function ######
You need to run the GUI code in the main thread, and your temperature reading code needs to be in the background thread. It's only safe to update the GUI in the main thread, so you can pass the temperature data you're reading from the background thread back to the main thread via a Queue, and have the main thread periodically check for data in the queue using self.root.after():
from Tkinter import *
import tkFont
import os
import glob
import time
import threading
import Image
import Queue
def update_temp(queue):
""" Read the temp data. This runs in a background thread. """
while True:
# 28-000005c6ba08
i = "28-000005c6ba08"
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + i)[0]
device_file = device_folder + '/w1_slave'
tempread=round(read_temp(),1)
# Pass the temp back to the main thread.
queue.put(tempread)
time.sleep(5)
class Gui(object):
def __init__(self, queue):
self.queue = queue
#Make the window
self.root = Tk()
self.root.wm_title("Home Management System")
self.root.minsize(1440,1000)
self.equipTemp = StringVar()
self.equipTemp1 = StringVar()
self.equipTemp2 = StringVar()
self.customFont = tkFont.Font(family="Helvetica", size=16)
# 1st floor Image
img = Image.open("HOUSE-PLANS-01.png")
photo = ImageTk.PhotoImage(img)
Label1=Label(self.root, image=photo)
Label1.place(x=100, y=100)
# 2nd floor
img2 = Image.open("HOUSE-PLANS-02.png")
photo2 = ImageTk.PhotoImage(img2)
Label1=Label(self.root, image=photo2)
Label1.place(x=600, y=100)
# Basement image
img3 = Image.open("HOUSE-PLANS-03.png")
photo3 = ImageTk.PhotoImage(img3)
Label1=Label(self.root, image=photo3)
Label1.place(x=100, y=500)
# Attic Image
img4 = Image.open("HOUSE-PLANS-04.png")
photo4 = ImageTk.PhotoImage(img4)
Label1=Label(self.root, image=photo4)
Label1.place(x=600, y=500)
# House Isometric Image
img5 = Image.open("house-iso.png")
photo5 = ImageTk.PhotoImage(img5)
Label1=Label(self.root, image=photo5)
Label1.place(x=1080, y=130)
#Garage Temp Label
Label2=Label(self.root, textvariable=self.equipTemp, width=6, justify=RIGHT, font=self.customFont)
Label2.place(x=315, y=265)
print "start monitoring and updating the GUI"
# Schedule read_queue to run in the main thread in one second.
self.root.after(1000, self.read_queue)
def read_queue(self):
""" Check for updated temp data"""
try:
temp = self.queue.get_nowait()
self.equipTemp.set(temp)
except Queue.Empty:
# It's ok if there's no data to read.
# We'll just check again later.
pass
# Schedule read_queue again in one second.
self.root.after(1000, self.read_queue)
if __name__ == "__main__":
queue = Queue.Queue()
# Start background thread to get temp data
t = threading.Thread(target=update_temp, args=(queue,))
t.start()
print "starting app"
# Build GUI object
gui = Gui(queue)
# Start mainloop
gui.root.mainloop()
Edit:
After actually taking a look at the tkinter source code, as well as the Python bug tracker, it appears that unlike almost every other GUI library out there, tkinter is intended to be thread-safe, as long you run the mainloop in the main thread of the application. See the answer I added here for more info, or go straight to the resolved issue about tkinter's thread safety on the Python bug tracker here. If the tkinter source and Python's bug tracker are correct, that would mean that as long as you run the mainloop in the main thread, you can happily call gui.equipTemp.set() directly from your temperature reading thread - no Queue required. And in my testing, that did indeed work just fine.
GUI toolkits are not threadsafe. You can only built and change your GUI from the main thread.
Since reading the temperature does not take that long, you can remove all the threading code and use the after-method from Tk.
Your read_temp_raw function is very complicated:
def read_temp_raw():
with open(device_file) as temp:
return temp.read().split('\n')

How to Open Multiple Tkinter windows in one window

I am having two or more python Tkinter files. Each file is opening one window, how can run all the Tkinter windows functionality in one main window.
Ex : I have two files one is usbcam.py which will open USB camera and give the video steaming and the other one is ipcam.py it opens the IP camera and give the live streaming.This two files are opening in two windows how can make this to work in one window
usbcam.py
import cv2
import PIL.Image
import PIL.ImageTk
import Tkinter as tk
def update_image(image_label, cv_capture):
cv_image = cv_capture.read()[1]
cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
pil_image = PIL.Image.fromarray(cv_image)
pil_image.save('image3.jpg')
tk_image = PIL.ImageTk.PhotoImage(image=pil_image)
image_label.configure(image=tk_image)
image_label._image_cache = tk_image # avoid garbage collection
root.update()
def update_all(root, image_label, cv_capture):
if root.quit_flag:
root.destroy() # this avoids the update event being in limbo
else:
update_image(image_label, cv_capture)
root.after(10, func=lambda: update_all(root, image_label, cv_capture))
if __name__ == '__main__':
cv_capture = cv2.VideoCapture()
cv_capture.open(0) # have to use whatever your camera id actually is
root = tk.Tk()
setattr(root, 'quit_flag', False)
def set_quit_flag():
root.quit_flag = True
root.protocol('WM_DELETE_WINDOW', set_quit_flag) # avoid errors on exit
image_label = tk.Label(master=root) # the video will go here
image_label.pack()
root.after(0, func=lambda: update_all(root, image_label, cv_capture))
root.mainloop()
ipcam.py
import cv2
import numpy as np
import PIL.Image
import PIL.ImageTk
import Tkinter as tk
import urllib
stream = urllib.urlopen("http://192.168.2.195:80/capture/scapture").read()
bytes_ = ''
def update_image(image_label):
global bytes_
bytes_ += stream.read(1024)
a = bytes_.find('\xff\xd8')
b = bytes_.find('\xff\xd9')
if (a != -1) and (b != -1):
jpg = bytes_[a:b+2]
bytes_ = bytes_[b+2:]
cv_image = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),
cv2.CV_LOAD_IMAGE_COLOR)
cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
pil_image = PIL.Image.fromarray(cv_image)
tk_image = PIL.ImageTk.PhotoImage(image=pil_image)
image_label.configure(image=tk_image)
image_label._image_cache = tk_image # avoid garbage collection
root.update()
def update_all(root, image_label):
if root.quit_flag:
print "coming if"
root.destroy() # this avoids the update event being in limbo
else:
print "coming else"
update_image(image_label)
root.after(1, func=lambda: update_all(root, image_label))
def timer(interval = 100):
root.after(0, func=lambda: update_all(root, image_label))
#.................................................................................................
root.after(interval, timer)
if __name__ == '__main__':
root = tk.Tk()
setattr(root, 'quit_flag', False)
def set_quit_flag():
root.quit_flag = True
root.protocol('WM_DELETE_WINDOW', set_quit_flag)
image_label = tk.Label(master=root) # label for the video frame
image_label.pack()
root.after(2, func=lambda: update_all(root, image_label))
# timer()
root.mainloop()
You need to designate one script as the main script, and in that one you can import the other. Here's an example of doing this using a simple subclass of the Frame widget:
The primary script (tkA.py):
from Tkinter import *
from tkB import Right # bring in the class Right from secondary script
class Left(Frame):
'''just a frame widget with a white background'''
def __init__(self, parent):
Frame.__init__(self, parent, width=200, height=200)
self.config(bg='white')
if __name__ == "__main__":
# if this script is run, make an instance of the left frame from here
# and right right frame from tkB
root = Tk()
Left(root).pack(side=LEFT) # instance of Left from this script
Right(root).pack(side=RIGHT) # instance of Right from secondary script
root.mainloop()
The secondary script (tkB.py):
from Tkinter import *
class Right(Frame):
'''just a frame widget with a black background'''
def __init__(self, parent):
Frame.__init__(self, parent, width=200, height=200)
self.config(bg='black')
if __name__ == "__main__":
# if this script is run, just do this:
root = Tk()
Right(root).pack()
root.mainloop()
Hope that helps.
First, you need to include it in the top. So in the top of ipcam.py write 'import usbcam' (without quotations).

Categories

Resources