RDS
Posts: 721
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

A picture in a tkinter window

Mon Dec 03, 2018 4:52 pm

I have created a few programs in tkinter and I am very pleased with the results.

My programs so far have been limited to a few buttons and drawing a shape in a tkinter frame.

I would now like to create a program that has some buttons but also a window within the overall tkinter frame that is used to display a picture or video taken by the Pi camera. Selecting one of the buttons will activate the camera.

Is it possible to display a picture using tkinter?

scotty101
Posts: 3732
Joined: Fri Jun 08, 2012 6:03 pm

Re: A picture in a tkinter window

Mon Dec 03, 2018 5:27 pm

Yep.

Tkinter out of the box supports GIF images but with the PIL library can support most of the common image formats.
http://effbot.org/tkinterbook/photoimage.htm

There is an example of a simple image viewing file written with python and tkinter here
https://gist.github.com/nakagami/3764702

I also believe that the latest versions of guizero (a wrapper for tkinter designed to make gui development more beginner friendly) contains support for most image formats using PIL.
https://lawsie.github.io/guizero/picture/
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

RDS
Posts: 721
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: A picture in a tkinter window

Mon Dec 03, 2018 6:01 pm

Thank you scotty.
Unless I have misunderstood the program, the examples shown seem to take the image from a file.
My intention would be to take the image directly from the camera and display it in the window, without saving it first. (sorry reading my initial post again, I did not make that clear)

User avatar
joseplaselva
Posts: 92
Joined: Tue Oct 04, 2016 4:45 am
Location: Kvilla , Sweden

Re: A picture in a tkinter window

Sat Jan 05, 2019 3:05 pm

May be this can help you,I use to take snapshots on a remote place and send the image by mail.
The script if for Python 2,7

Code: Select all

# Created 2018-Juni-12  14:10
# Tkinter issue
# Modified i la Selva 18-December-13  11:07
from Tkinter import *

from PIL import Image, ImageTk

import picamera
import time
import datetime
import shutil
import smtplib
import os
import tkMessageBox


from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
from email.mime.image import MIMEImage

fromaddr ="[email protected]"
toaddr = "[email protected]"
mailpass = "xxxxxxxxx"



bilder = "noimage.jpg"
shotflag = 0
texmed = " "

root = Tk()
w = 855 # width for the Tk root
h = 785 # height for the Tk root
root.title("ARBETSBOD - SNAPSHOT")

# estableix que no es pot redimensionar
root.resizable(0, 0)
# get screen width and height
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen

# calculate x and y coordinates for the Tk root window
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)

# set the dimensions of the screen 
# and where it is placed
root.geometry('%dx%d+%d+%d' % (w, h, x, y))

camera = picamera.PiCamera()
#camera.awb_mode = 'auto'
camera.brightness = 50
camera.rotation= 90
camera.resolution = (2592, 1944)
data=""

class fotomail:
    def __init__(self, master):
        self.etPicture = Label(root, font=('arial narrow', 14, 'normal'))
        self.etPicture.grid(row=0, rowspan=4, column=0, columnspan=2, padx=6, pady=6, sticky=NSEW)

        self.textBox = Text(root, height=1, width=1, relief=SUNKEN, font=('arial narrow', 10, 'normal'), bg="green",
                            fg="white")
        self.textBox.grid(row=4, rowspan=2, column=0, padx=3, pady=2, sticky=NSEW)
        self.textBox.insert(END, "READY")

        self.textBox1 = Text(root, height=1, width=1, relief=SUNKEN, font=('arial narrow', 10, 'normal'), bg="green",
                             fg="white")
        self.textBox1.grid(row=4, rowspan=2, column=1, padx=3, pady=2, sticky=NSEW)

        self.botshoot = Button(root, width=18, font=('arial narrow', 19, 'normal'), text="TAKE A PHOTO",
                               activebackground="#00dfdf")
        self.botshoot.grid(row=6, rowspan=1, column=0, columnspan=2, ipady=15, pady=2, padx=2, sticky=NSEW)
        self.botshoot.configure(command=self.capture_image)

        self.botMail = Button(root, height=2, font=('arial', 18, 'normal'), text="EMAIL FOTO",
                              activebackground="#00dfdf", state=DISABLED)
        self.botMail.grid(row=8, rowspan=2, column=0, columnspan=2, pady=1, sticky=NSEW)
        self.botMail.configure(command=self.sendMail)

 
        self.botQuit = Button(root, heigh=2, font=('arial', 18, 'normal'), text="QUIT", activebackground="#00dfdf")
        self.botQuit.grid(row=15, rowspan=2, column=0, columnspan=2, pady=0, sticky=NSEW)
        self.botQuit.configure(command=self.closewindow)

        self.showImg()

    def capture_image(self):
        global shot
        global texte
        global texmed
        global shotflag
        if shotflag ==1:
            self.radera()
        
        data = time.strftime("%Y-%b-%d_(%H%M%S)")
        texte = "picture take:" + data
        dagtid = time.strftime("%y-%b-%d (%H:%M)")
        camera.start_preview()
        
##      camera.capture('%s.jpg' % data, resize=(840, 525))
        camera.capture('%s.jpg' % data)
        camera.stop_preview()
        time.sleep(1)
        shot = '%s.jpg' % data
        self.textBox.delete("1.0", END)
        self.textBox.insert(END,'%s' % data)
        self.textBox1.delete("1.0", END)
        self.textBox1.insert(END,"   CAPTURED file: " + shot)
       
        texmed = "Arbetsbod-Kam " + dagtid
        self.botshoot.configure(state=NORMAL)
        self.botMail.configure(state=NORMAL)
        self.botQuit.configure(state=NORMAL)
        shotflag = 1
        self.showImg()
        
        
    def showImg(self):
        if shotflag ==0:
            image = Image.open(bilder)
        else:
            image = Image.open(shot)
            
        image = image.resize((840,525),Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)
        
        self.etPicture.configure(image=photo)
        self.etPicture.image=photo
        root.update_idletasks()




    def sendMail(self):
        global texte
        global shot
        global dat
        global texmed
        self.botMail.configure(state=DISABLED)
        self.botshoot.configure(state=DISABLED)
        self.botQuit.configure(state=DISABLED)

        mail = MIMEMultipart()
        mail['Subject'] =   str(texmed)
        mail['From'] = fromaddr
        mail['To'] = toaddr
        mail.attach(MIMEText(texte, 'plain'))

        self.textBox1.delete("1.0", END)
        self.textBox1.insert(END,"PREPARING TO SEND PICTURE BY MAIL")
        self.textBox1.update_idletasks()
        
        dat = '%s.jpg' % data
        attachment = open(shot, 'rb')
        image = MIMEImage(attachment.read())
        attachment.close()
        mail.attach(image)
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(fromaddr, mailpass)
        text = mail.as_string()
        server.sendmail(fromaddr, toaddr, text)
        server.quit()
        self.textBox.delete("1.0", END)
        self.textBox.insert(END,shot)
        self.textBox1.delete("1.0", END)
        self.textBox1.insert(END," SENT TO: [email protected] AND DELETED ")

        self.botshoot.configure(state=NORMAL)
        self.botQuit.configure(state=NORMAL)

    def radera(self):
        pic = shot
        os.remove(pic)
    def closewindow(self):
        if shotflag ==1:
            self.radera()
        root.destroy()


fotomail(root)
root.mainloop()
Last edited by joseplaselva on Sat Jan 05, 2019 5:17 pm, edited 1 time in total.

RDS
Posts: 721
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: A picture in a tkinter window

Sat Jan 05, 2019 3:15 pm

@joseplaselva
Thank you very much.
I have been following your other recent thread, with great interest but I have so far been unable to get the program running for the reasons I have posted on that thread.
Would it be possible please to edit your post above to ensure that the code is formatted correctly (select it all and then click the 'Code' button) so that all the indents that are critical to Python, are displayed.
Thanks again, I really look forward to getting this working.
Last edited by RDS on Sun Jan 06, 2019 4:51 pm, edited 1 time in total.

User avatar
joseplaselva
Posts: 92
Joined: Tue Oct 04, 2016 4:45 am
Location: Kvilla , Sweden

Re: A picture in a tkinter window

Sat Jan 05, 2019 5:18 pm

post edited

RDS
Posts: 721
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: A picture in a tkinter window

Sat Jan 05, 2019 11:03 pm

@joseplaselva
Thank you very much.
The only changes I had to make (after selecting Python 2) was to type:

Code: Select all

sudo apt-get install python-imaging-tk
into the Terminal Window and then to select one of my own jpg's on my pi, to start with.

Over the next few days I will add my own email details and then maybe in the future, try to convert the program to Python3 which is my preferred version.

This is a great start for something I have wanted to do for quite a while, thanks again.

Return to “Python”