Opening images from 2 folders and displaying them simultaneously in python - python

I would like to open images from 2 different folders and display them next to each other , also have a button " Next" to be able to move to the next pair of images.
The images paths are stored in a txt file , so lets say open the first image and the second image and when I click next , 3rd and 4th image and so on
I am new to python and this is what I found so far to read an image
from Tkinter import *
from PIL import ImageTk, Image
import os
root = Tk()
img = ImageTk.PhotoImage(Image.open("path.ppm"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()
But i can't figure how to open 2 images simultaneously and add the next button

Here is a working example of what you ask:
from tkinter import *
def UpdateImg ( ):
global img1, img2
img1 = PhotoImage(file=ImgFiles[Cur])
img2 = PhotoImage(file=ImgFiles[Cur+1])
LblImg1.configure(image = img1, text=ImgFiles[Cur])
LblImg2.configure(image = img2, text=ImgFiles[Cur+1] )
def BtnNext( ):
global Cur
if Cur < len(ImgFiles)-2:
Cur = Cur + 2
UpdateImg ( )
def BtnPrev( ):
global Cur
if Cur > 1:
Cur = Cur - 2
UpdateImg ( )
fp = open("ImgFilesSrc.txt", "r")
ImgFiles = fp.read().split('\n')
fp.close()
Cur = 0
img1 = img2 = ''
root = Tk()
#Create the main Frame -----------------------------------------------------------------
FrmMain = Frame(root)
LblImg1 = Label(FrmMain, text = "Picture 1", anchor=W, width=120, bg="light sky blue")
LblImg2 = Label(FrmMain, text = "Picture 2", anchor=W, width=120, bg="light sky blue")
BtnPrev = Button(FrmMain, text=" < ", width=10, command=BtnPrev)
BtnNext = Button(FrmMain, text=" > ", width=10, command=BtnNext)
LblImg1.grid (row=2, rowspan = 3, column=1, columnspan=3);
LblImg2.grid (row=2, rowspan = 3, column=4, columnspan=3);
BtnPrev.grid (row=5, column=2); BtnNext.grid(row=5, column=4)
FrmMain.pack(side=TOP, fill=X)
#--------------------------------------------------------------------------
UpdateImg ( )
root.mainloop()

Related

Unable to create elements within notebook tab python tkinter

I have 2 files where I want to put a list of images from my database into my tkinter notebook tab upon searching through my database. However I am unable to do so as when I execute the search button , my tab which the images and details should be populated into still it remains empty. In addition, the details are only shown when I closed the initial application in which a second application will then open to show the details. However what I want is for the details to be populated straightaway into my tkinter notebook tab. Can I ask for some guidance on how I should amend my code?
from cProfile import label
from tkinter import *
from PIL import ImageTk, Image
from tkinter import ttk
root = Tk()
root.geometry("1300x600")
my_tabs = ttk.Notebook(root)
my_tabs.pack()
# style = ttk.Style()
# style.layout("TNotebook.Tab", [])
def back():
my_tabs.select(0)
def back1():
my_tabs.select(1)
def back2():
my_tabs.select(2)
def whenClicked():
global entry
entry = enTree.get()
print(entry,type(entry))
my_tabs.select(1)
my_frame = Frame(my_tabs, width=1300, height=600)
my_frame2 = Frame(my_tabs, width=1300, height=600)
my_frame3 = Frame(my_tabs, width= 1300, height=600)
my_frame4 = Frame(my_tabs, width= 1300, height=600)
my_frame5 = Frame(my_tabs, width= 1300, height=600)
my_frame6 = Frame(my_tabs, width= 1300, height=600)
my_frame.pack(fill="both", expand=1)
my_frame2.pack(fill="both", expand=1)
my_frame3.pack(fill="both", expand=1)
my_frame4.pack(fill="both", expand=1)
my_frame5.pack(fill="both", expand=1)
my_frame6.pack(fill="both", expand=1)
my_tabs.add(my_frame, text="1st tab")
my_tabs.add(my_frame2, text="2nd tab")
my_tabs.add(my_frame3, text="3rd tab")
my_tabs.add(my_frame4, text="4th tab")
my_tabs.add(my_frame5, text="5th tab")
my_tabs.add(my_frame6, text="6th tab")
img = (Image.open("Iphone.jfif"))
resizedImage = img.resize((300, 300), Image.ANTIALIAS)
img2 = ImageTk.PhotoImage(resizedImage)
img3 = (Image.open("Rating.png"))
resizedImage2 = img3.resize((300, 60), Image.ANTIALIAS)
img4 = ImageTk.PhotoImage(resizedImage2)
img5 = (Image.open("Cheese.png"))
resizeImage3 = img5.resize((80,80), Image.ANTIALIAS)
CheesePic = ImageTk.PhotoImage(resizeImage3)
emptyLabel = Label(my_frame)
emptyLabel.pack(pady=80)
#App name/Label
labelOne = Label(my_frame, text = "Compario", font=("Algerian", 50))
labelOne.pack(padx=10,pady=10, anchor=CENTER)
#Search box
enTree = Entry(my_frame, width=60, font=30)
enTree.pack(padx=10,pady=10, ipady=7, anchor=CENTER)
#Search button
buttonOne = Button(my_frame, text = "Search", font=("Arial", 15), padx=25, pady=6, fg="white", bg="grey", command=whenClicked)
buttonOne.pack(padx=10,pady=10,anchor=CENTER)
backButton = Button(my_frame2, text = "Back", command = back)
backButton.place(relx=0.07, rely=0.1, anchor=CENTER)
root.mainloop()
Here is my second file
from tkinter import *
from PIL import ImageTk, Image
from io import BytesIO
import requests
import sqlite3
import GUI3
root = Tk()
root.geometry("1300x600")
#Database output result from site into GUI
Links = []
PName = []
Price = []
Rating = []
a = []
b = []
c = []
d= []
def fetch_db():
connection = sqlite3.connect("site.db")
cursor = connection.cursor()
cursor.execute("SELECT IMAGE FROM products WHERE TITLE LIKE ?", ("%" + GUI3.entry + "%",))
all_tables = cursor.fetchall()
for row in all_tables[:4]:
Links.append(row)
for lItems in Links:
for lItem in lItems:
continue
a.append(lItem)
cursor.execute("SELECT TITLE FROM products WHERE TITLE LIKE ?", ("%" + GUI3.entry + "%",))
all_tables2 = cursor.fetchall()
for row in all_tables2[:4]:
PName.append(row)
for pdItems in PName:
for pdItem in pdItems:
continue
b.append(pdItem)
cursor.execute("SELECT PRICE FROM products WHERE TITLE LIKE ?", ("%" + GUI3.entry + "%",))
all_tables3 = cursor.fetchall()
for row in all_tables3[:4]:
Price.append(row)
for pItems in Price:
for pItem in pItems:
continue
c.append(pItem)
cursor.execute("SELECT RATING FROM products WHERE TITLE LIKE ?", ("%" + GUI3.entry + "%",))
all_tables4 = cursor.fetchall()
for row in all_tables4[:4]:
Rating.append(row)
for rItems in Rating:
for rItem in rItems:
continue
d.append(rItem)
connection.close()
fetch_db()
for z in range(0, len(a)):
r = requests.get(str(a[z]))
phoneImage = Image.open(BytesIO(r.content)).resize((160, 160), Image.Resampling.LANCZOS)
photo = ImageTk.PhotoImage(phoneImage)
label = Label(image=photo)
label.image = photo
bigB = str(b[z])
bigC = str(c[z])
bigD = str(d[z])
labelImage = Label(GUI3.my_frame2, text ="Hello Educba Technology Institute")
labelText = Label(GUI3.my_frame2, width=22, text=bigB, bg="white").place(x=10+(z+1)*200, y=190)
labelPrice = Label(GUI3.my_frame2, width=20, text=bigC, bg="white").place(x=20+(z+1)*200, y=220)
labelRating = Label(GUI3.my_frame2, width=20, text=bigD+"/5", bg="white").place(x=20+(z+1)*200, y=250)
z += 1

How to make a image viewer with left right functionality in tkinter?

I have bunch of links and labels in list to view those I want to make a image viewer with next, previous functionality. My links and labels for respective images are in list. Up to now I had tried this :
urls=[url,url1,url2,url3]
labels=["label 1","label 2","label 3","label 4"]
images=[]
for ur in urls:
raw_data = urllib.request.urlopen(ur).read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
images.append(image)
Now I have images ready in images and now I want to display it in image viewer but only last image is visible in image viewer.
Label(root).grid(row=1,column=1)
for i in range(len(images)):
image_label=Label(root,image=images[i])
image_label.grid(row=1,column=2)
name=Label(root,text=labels[i])
name.grid(row=2,column=2)
def left():
image_label=Label(root,image=images[i-1])
image_label.grid(row=1,column=2)
def right():
image_label=Label(root,image=images[i+1])
image_label.grid(row=1,column=2)
left_button=Button(root,text="Left",command=left)
left_button.grid(row=2,column=1)
right_button=Button(root,text="Right",command=right)
right_button.grid(row=2,column=3)
Right button is not working and left button is working but for one time only. When I click left button second time then nothing is working.
Error while clicking in right button :
line 45, in right
image_label=Label(root,image=images[i+1])
IndexError: list index out of range
The code is pretty close to original posted example.
There is no lambda in Button, just straight forward command that gives access to left and right functions.
The name label is unnecessary as label objects already have a text attribute so I've integrated image and text into single label and increased the font size.
label compound is used to control where the image is display relative to the text, I've chosen top. That is, the image will be place above the text.
The use of global in functions keeps track of count
from tkinter import Tk, Label, Frame, Button
from PIL import ImageTk, Image
import io
import requests
import urllib
root = Tk()
urls = [url, url1, url2, url3]
labels = ["label 1","label 2","label 3","label 4"]
count = -1
images = []
for ur in urls:
raw_data = urllib.request.urlopen( ur ).read()
im = Image.open(io.BytesIO( raw_data ))
image = ImageTk.PhotoImage(im)
images.append(image)
def left( ):
global count
count = (count - 1) % len(images)
image_label.config(image = images[count], text = labels[count])
def right( ):
global count
count = (count + 1) % len(images)
image_label.config(image = images[count], text = labels[count])
image_label = Label(
root, image = images[count], font = "Helvetica 20 normal",
text = labels[count], compound = "top")
image_label.grid(row = 0, column = 0, columnspan = 2, sticky = "nsew")
Button(
root, text = "<< LEFT", command = left).grid( row = 1, column = 0, sticky = "ew")
Button(
root, text = "RIGHT >>", command = right).grid(row = 1, column = 1, sticky = "ew")
right( ) # display first image
root.mainloop()
Here's a way to do it by showing and hiding pairs of Labels with the image and it name on them. For development and testing purposes, it loads the images from disk instead of downloading them, but you can easily replace that with what you have in your question.
from pathlib import Path
from PIL import Image, ImageTk
from tkinter import Button, Tk, Label
root = Tk()
root.title('Image Viewer')
# Create thumbnails of all the images.
image_folder = '/path/to/image/folder'
images = []
for filepath in Path(image_folder).iterdir():
img = Image.open(filepath)
w, h = img.size
if w > h:
f = 100 / w
nw, nh = 100, int(f*h)
else:
f = 100 / h
nw, nh = int(f*w), 100
# Offsets to center thumbnail within (100, 100).
woff, hoff = (100-nw) // 2, (100-nh) // 2
img = img.resize((nw, nh), Image.BICUBIC) # Shrink so largest dimen is 100.
thumbnail = Image.new('RGBA', (100, 100), (255, 255, 255, 0)) # Blank.
thumbnail.paste(img, (woff, hoff)) # Offset keep it centered.
images.append(ImageTk.PhotoImage(thumbnail))
names = ['Name 1', 'Name 2', 'Name 3', 'Name 4']
def get_images():
"""Create all image and name Label pairs but initially hidden."""
global image_labels, name_labels
image_labels, name_labels = [], []
for i, (img, name) in enumerate(zip(images, names)):
image_label = Label(root, image=img)
image_label.grid(row=1, column=2)
image_labels.append(image_label)
name_label = Label(root, text=name)
name_label.grid(row=2, column=2)
name_labels.append(name_label)
hide(i)
def hide(i):
"""Hide specified image and name pair."""
image_labels[i].grid_remove()
name_labels[i].grid_remove()
def show(i):
"""Unhide specified image and name pair."""
image_labels[i].grid()
name_labels[i].grid()
def shift(direction):
"""Display the image and pair before or after the current one that is
`direction` steps away (usually +/-1).
"""
global current
hide(current)
current = (current + direction) % len(images)
show(current)
left_button = Button(root, text="Left", command=lambda: shift(-1))
left_button.grid(row=2, column=1)
right_button = Button(root, text="Right", command=lambda: shift(+1))
right_button.grid(row=2, column=3)
get_images()
current = 0 # Currently displayed image.
show(current)
root.mainloop()
Screenshot of it running:
Should just update a image label when shift left or right, not create a new label.
Using modulus % to find which one next turn.
To reduce code and executable, I use the image data in PySimpleGUI and simple name for image here.
import tkinter as tk
import PySimpleGUI as sg
def shift(num):
global index
index = (index + num) % size
label1.configure(image=images[index])
label2.configure(text =labels[index])
root = tk.Tk()
images = [tk.PhotoImage(data=image) for image in sg.EMOJI_BASE64_HAPPY_LIST]
size = len(images)
labels = [f'Image {i:0>2d}' for i in range(size)]
index = 0
label1 = tk.Label(root, image=images[index])
label1.grid(row=1, column=2)
label2 = tk.Label(root, text=labels[index])
label2.grid(row=2, column=2)
button1 = tk.Button(root, text="<LEFT", width=6, anchor='center', command=lambda num=-1:shift(num))
button1.grid(row=1, column=1)
button2 = tk.Button(root, text="RIGHT>", width=6, anchor='center', command=lambda num=+1:shift(num))
button2.grid(row=1, column=3)
root.mainloop()
You can try this :
from tkinter import Tk,Label,Button
from PIL import ImageTk,Image
import io
import requests
import urllib
root=Tk()
count=0 # To know the current image and label
urls=[url,url1,url2,url3]
labels=["label 1","label 2","label 3","label 4"]
images=[]
for ur in urls:
raw_data = urllib.request.urlopen(ur).read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
images.append(image)
def change(direction): # Function to change image
global count
if direction=="left":
if count<=0:
count=len(urls)-1
else:
count-=1
else:
if count>=len(urls)-1:
count=0
else:
count+=1
name.config(text=labels[count])
image_label.config(image=images[count])
Label(root).grid(row=1,column=1)
image_label=Label(root,image=images[count])
image_label.grid(row=1,column=2)
left_button=Button(root,text="Left",command=lambda : change("left"))
left_button.grid(row=2,column=1)
name=Label(root,text=labels[count])
name.grid(row=2,column=2)
right_button=Button(root,text="Right",command=lambda : change("right"))
right_button.grid(row=2,column=3)
root.mainloop()

how to display blob as image in a table in tkinter python

I am trying to insert and retrieve image from MySQL database.I have inserted the image as BLOB (longblob). When I am able to display it using image.show() but I want the image to be displayed in a table.
I used treeview for this purpose. But my table shows only BLOB objects. It doesn't show any image.
This is my code.
from tkinter import *
from PIL import ImageTk,Image
from tkinter import filedialog
import mysql.connector
import io
from tkinter import ttk
root = Tk()
id = Entry(root, width=10, font=("Helvetica", 20), bd=3)
id.pack()
browse_button = Button(root,text ='Browse',command = lambda:open_file())
browse_button.pack()
display_button = Button(root,text ='display',command =lambda:display_file())
display_button.pack()
display_table_button = Button(root,text ='display Table',command =lambda:display_Table())
display_table_button.pack()
def display_Table():
query = "SELECT * FROM image_db"
person = mysql.connector.connect(host="localhost", user="root", password="", database="image")
cursor_variable = person.cursor()
cursor_variable.execute(query)
vertical_scrollbar = ttk.Scrollbar(root)
vertical_scrollbar.pack(side=RIGHT, fill=Y)
my_tree = ttk.Treeview(root, yscrollcommand= vertical_scrollbar.set)
my_tree.pack()
vertical_scrollbar.config(command= my_tree.yview)
style = ttk.Style(root)
style.theme_use("winnative")
style.configure(".", font=("Helvetica", 11))
style.configure("Treeview.Heading", font=("Helvetica", 11, "bold"))
my_tree['columns'] = ("id", "data")
my_tree.column("#0", width=0, stretch='NO')
my_tree.column("id", width=50, anchor='w')
my_tree.column("data", width=130, anchor='w')
my_tree.heading("#0", anchor='w', text='Label')
my_tree.heading("id", anchor='w', text="Id")
my_tree.heading("data", anchor='w', text="Image")
count = 0
for record in cursor_variable:
# print(record)
my_tree.insert(parent='', index='end', iid=count, text='Parent',
values=(record[0], record[1]))
count += 1
person.close()
def display_file():
id2 = id.get()
person = mysql.connector.connect(host="localhost", user="root", password="", database="image")
cursor_variable = person.cursor()
sql = "SELECT data FROM image_db WHERE id = '" + id2 + "'"
cursor_variable.execute(sql)
all_data = cursor_variable.fetchall()
image = all_data[0][0]
image = Image.open(io.BytesIO(image))
image.show()
person.commit()
person.close()
def open_file():
root.filename = filedialog.askopenfilename(initialdir="/Users/write/PycharmProjects/slider/img", title='Select a File',
filetypes=(('png files', '*.png'), ('jpeg files', '*.jpeg'),
('jpg files', '*.jpg')))
my_label = Label(root, text=root.filename).pack()
my_image = ImageTk.PhotoImage(Image.open(root.filename))
path = root.filename
id1 = id.get()
person = mysql.connector.connect(host="localhost", user="root", password="", database="image")
cursor_variable = person.cursor()
thedata = open(root.filename, 'rb').read()
sql = "INSERT INTO image_db (id,data) VALUES ('" + id1 + "',%s)"
cursor_variable.execute(sql, (thedata,))
person.commit()
person.close()
root.mainloop()
Any help is appreciated.
I have modified your display_Table():
set the rowheight of treeview to 50
set width of column "#0" to 100
resize the retrieved image to fit the treeview cell
def display_Table():
...
style = ttk.Style(root)
style.theme_use("winnative")
style.configure(".", font=("Helvetica", 11))
style.configure("Treeview.Heading", font=("Helvetica", 11, "bold"))
style.configure("Treeview", rowheight=50) # set row height
my_tree['columns'] = ("id",)
my_tree.column("#0", width=100, stretch='NO') # set width
my_tree.column("id", width=100, anchor='w')
my_tree.heading("#0", anchor='w', text='Image')
my_tree.heading("id", anchor='w', text="Id")
count = 0
my_tree.imglist = []
for record in cursor_variable:
img = Image.open(io.BytesIO(record[1]))
img.thumbnail((50,50)) # resize the image to desired size
img = ImageTk.PhotoImage(img)
my_tree.insert(parent="", index="end", iid=count,
image=img, values=(record[0],)) # use "image" option for the image
my_tree.imglist.append(img) # save the image reference
count += 1
Note that I have used a list to hold the image references to avoid garbage collection.
The output:

How can i print some features in python opencv GUI?

I want to print the mean, height & width of an image in python openCV. Where i used two button (get photo and analysis image) and different GUI,one for getting the photo(def openphoto(): ) and another for printing those features(def feature(): ). But I'm getting error.
N.B. full code is too long.so, i used some part of it.
I've tried it in python openCV.
import tkinter as tk
from tkinter.filedialog import askopenfilename
import shutil
import os
from PIL import Image, ImageTk
window = tk.Tk()
window.title("Dr. Papaya")
window.geometry("500x510")
window.configure(background ="lightgreen")
title = tk.Label(text="Click below to choose picture for testing disease....", background = "lightgreen", fg="Brown", font=("", 15))
title.grid()
def feature():
window.destroy()
window1 = tk.Tk()
window1.title(" ")
window1.geometry("650x510")
window1.configure(background="lightgreen")
def exit():
window1.destroy()
#i want to print here
print("Mean : ",mean)
print("Heigth : ",heigth)
print("Width : ",width)
button = tk.Button(text="Exit", command=exit)
button.grid(column=0, row=9, padx=20, pady=20)
window1.mainloop()
def openphoto():
import cv2
import numpy as np
fileList = os.listdir(dirPath)
for fileName in fileList:
os.remove(dirPath + "/" + fileName)
fileName = askopenfilename(initialdir='', title='Select image for analysis ',
filetypes=[('image files', '.jpg')])
dst = " "
shutil.copy(fileName, dst)
load = Image.open(fileName)
#calculate the mean
mean=np.mean(load)
#calculate the height & width
height = np.size(load, 0)
width = np.size(load, 1)
render = ImageTk.PhotoImage(load)
img = tk.Label(image=render, height="250", width="500")
img.image = render
img.place(x=0, y=0)
img.grid(column=0, row=1, padx=10, pady = 10)
title.destroy()
button1.destroy()
button2 = tk.Button(text="Analyse Image", command=feature)
button2.grid(column=0, row=2, padx=10, pady = 10)
button1 = tk.Button(text="Get Photo", command = openphoto)
button1.grid(column=0, row=1, padx=10, pady = 10)
window.mainloop()
The variables are not in scope when you try to print them. This is an important programming principle so I suggest you read this introduction
You can make the variable global to make the them accessible outside of the function:
def openphoto():
global width, height, mean
[rest of code]

How to print values in GUI from image in python?

I'm new in GUI developing.Here i'hv created two GUI, one for taking photo and another for showing features.so,i'hv used two functions.but i don't know some things.Now i need two kinds of help from you.
1)what is the command for printing float value in GUI(not on console)?
2)How to calculate the value of mean,variance ,s.d. etc from a image and how to pass those values from one function to another function?
import tkinter as tk
from tkinter.filedialog
import askopenfilename
import shutil
import os
from PIL import Image, ImageTk
window = tk.Tk()
window.title(" ")
window.geometry("500x510")
window.configure(background ="lightgreen")
title = tk.Label(text="Click below to choose picture for testing disease....", background = "lightgreen", fg="Brown", font=("", 15))
title.grid()
def feature():
window.destroy()
window1 = tk.Tk()
window1.title(" ")
window1.geometry("650x510")
window1.configure(background="lightgreen")
def exit():
window1.destroy()
#i want to print some features of image e.g. Mean, variance,s.d. Etc.
button = tk.Button(text="Exit", command=exit)
button.grid(column=0, row=9, padx=20, pady=20)
window1.mainloop()
def openphoto():
import cv2
import numpy as np
dirPath = " "
fileList = os.listdir(dirPath)
for fileName in fileList:
os.remove(dirPath + "/" + fileName)
fileName = askopenfilename(initialdir='', title='Select image for analysis ',
filetypes=[('image files', '.jpg')])
dst = " "
shutil.copy(fileName, dst)
#this is the image
Photo = Image.open(fileName)
render = ImageTk.PhotoImage(photo)
img = tk.Label(image=render, height="250", width="500")
img.image = render
img.place(x=0, y=0)
img.grid(column=0, row=1, padx=10, pady = 10)
title.destroy()
button1.destroy()
button2 = tk.Button(text="Analyse Image", command=feature)
button2.grid(column=0, row=2, padx=10, pady = 10)
button1 = tk.Button(text="Get Photo", command = openphoto)
button1.grid(column=0, row=1, padx=10, pady = 10)
window.mainloop()
Okay, I took some more time to look into it.
Concerning the calculation of the values, your previous question did that correct, however the variables needed to be accessible globally. Concerning the displaying of a text, you have to add a tkinter text widget. If you want to add more calculated values, just google for numpy + 'value your want'.
I've taken your code and created a working example, see the code below. Note that I removed some stuff that wasn't neede for the example, so copy the lines you need to your own code. Also check out this reference for the text widget.
Result:
Code:
Note: I created 2 text widgets deliberately, to show 2 ways of implementing multiple texts
import tkinter as tk
from tkinter.filedialog import askopenfilename
import shutil
import os
from PIL import Image, ImageTk
window = tk.Tk()
window.title(" ")
window.geometry("500x510")
window.configure(background ="lightgreen")
title = tk.Label(text="Click below to choose picture for testing disease....", background = "lightgreen", fg="Brown", font=("", 15))
title.grid()
def feature():
window.destroy()
window1 = tk.Tk()
window1.title(" ")
### create a text widget, place it in window1 and insert the text
width_txt = tk.Text(window1, height=2, width=30, fg="RED", background = "lightgreen", relief="flat")
width_txt.grid(column=0, row=0)
width_txt.insert(tk.END, "Width: " + str(width))
height_txt = tk.Text(window1, height=2, width=30, fg="RED", background = "lightgreen", relief="flat")
height_txt.grid(column=0, row=1)
height_txt.insert(tk.END, "Height: " + str(height) + "\nMean: " + str(mean))
window1.geometry("650x510")
window1.configure(background="lightgreen")
def openphoto():
### this line makes the variables accessible everywhere
global width,height, mean
import numpy as np
fileName = askopenfilename(initialdir='', title='Select image for analysis ',
filetypes=[('image files', '.jpg')])
photo = Image.open(fileName)
#### calculate values
height = np.size(photo, 0)
width = np.size(photo, 1)
mean = np.mean(photo)
render = ImageTk.PhotoImage(photo)
img = tk.Label(image=render, height="250", width="500")
img.image = render
img.place(x=0, y=0)
img.grid(column=0, row=1, padx=10, pady = 10)
title.destroy()
button1.destroy()
button2 = tk.Button(text="Analyse Image", command=feature)
button2.grid(column=0, row=2, padx=10, pady = 10)
button1 = tk.Button(text="Get Photo", command = openphoto)
button1.grid(column=0, row=1, padx=10, pady = 10)
window.mainloop()

Categories