What I'm trying to do is to display the image cover from a flac file like in the pic below (this one is hard coded).
I ripped the cover with the function getCoverFlac from my code, but the problem begins when I try to update this img with my imgSet fucntion, the image to load exist(can see it in the dir and can even be used hard coded), but the image wont appear in the Ttkinter window. I believe its receiving the right file name since it returns the name correctly:
name of cover to display:Shikao Suga - Yuudachi ('99 NHK Hall 0 Live).flacCover.jpg
so how can I fix this?
full code bellow:
import pygame
import tkinter as tkr
from tkinter.filedialog import askdirectory
from tkinter import *
import os
from mutagen.flac import FLAC, Picture
import os.path
from PIL import ImageTk, Image
music_player = tkr.Tk()
cont = 0
music_player.title("My Music Player")
music_player.geometry("600x600")
play_list = tkr.Listbox(music_player, font="Helvetica 12 bold", bg='yellow', selectmode=tkr.SINGLE)
pygame.init()
pygame.mixer.init()
def play():
pygame.mixer.music.load(play_list.get(tkr.ACTIVE))
#gets and set the var name
var.set(play_list.get(tkr.ACTIVE))
#gets the cover and sets the the img that will be in panel
getThecover = getCoverFlac(play_list.get(tkr.ACTIVE))
imgSet(getThecover)
pygame.mixer.music.play()
def stop():
pygame.mixer.music.stop()
def pause():
pygame.mixer.music.pause()
def unpause():
pygame.mixer.music.unpause()
def selectDir():
directory = askdirectory()
os.chdir(directory)
song_list = os.listdir()
for item in song_list:
pos = 0
play_list.insert(pos, item)
pos += 1
def getCoverFlac(flac_file):
#this fucntion extracts the image from the flac file and saves it in the dir where the flac file is.
flacObj = FLAC(flac_file)
coverArt = flacObj.pictures
coverName = str(flac_file)+"Cover.jpg"
if os.path.isfile(coverName):
print(coverName+" already exists")
else:
for img in coverArt:
if img.type == 3:
with open(coverName, "wb") as f:
f.write(img.data)
print(coverName+" created and saved")
#img.show()
return coverName
def imgSet(var):
#sets the global var "img" to var
global img
print("name of cover to display:"+var)
resizeImg(var)
img = ImageTk.PhotoImage(Image.open(var))
def resizeImg(imgName):
basewidth = 300
img = Image.open(imgName)
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save(imgName)
Button1 = tkr.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="PLAY", command=play, bg="blue", fg="white")
Button2 = tkr.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="STOP", command=stop, bg="red", fg="white")
Button3 = tkr.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="PAUSE", command=pause, bg="purple", fg="white")
Button4 = tkr.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="UNPAUSE", command=unpause, bg="orange", fg="white")
Button5 = tkr.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="Music Dir", command=selectDir, bg="green", fg="white")
var = tkr.StringVar()
song_title = tkr.Label(music_player, font="Helvetica 12 bold", textvariable=var)
resizeImg('Haddaway - What Is Love (70 Mix).flacCover.jpg')
img = ImageTk.PhotoImage(Image.open('Haddaway - What Is Love (70 Mix).flacCover.jpg'))
panel = tkr.Label(music_player, image = img, justify=CENTER)
song_title.pack()
panel.pack(fill="x")
Button1.pack(fill="x")
Button2.pack(fill="x")
Button3.pack(fill="x")
Button4.pack(fill="x")
Button5.pack(fill="x")
play_list.pack(fill="both", expand="yes")
music_player.mainloop()
You just update the global variable img inside imageSet(), but forget to update the image of the label using panel.config(image=img):
def imgSet(var):
#sets the global var "img" to var
global img
print("name of cover to display:"+var)
resizeImg(var)
img = ImageTk.PhotoImage(Image.open(var))
panel.config(image=img) # update image of label "panel"
Related
I was making python gui with tkinter
I wanted to change button's image if I push button
But it doesn't work.(I use config)
with some effort I found it work in main code
but still it doesn't work in fucntion that is connected to button
Here are the codes
from tkinter import *
from PIL import Image, ImageTk
# using by function
def select_precision():
overheal = image_resize((20, 20), "gui_project/item_simulation/overheal.png")
runepage_00.config(image=overheal)
def image_resize(size, link):
image = Image.open(link)
image = image.resize(size, Image.ANTIALIAS)
image = ImageTk.PhotoImage(image)
return image
root = Tk()
root.title()
precision = PhotoImage(file="gui_project/item_simulation/precision.png")
rune00 = PhotoImage(file="gui_project/item_simulation/domination.png")
runepage_precision = Button(root, width=20, height=20,\
image=precision, command=select_precision)
runepage_00 = Button(root, width=20, height=20, image=rune00)
runepage_precision.pack()
runepage_00.pack()
root.mainloop()
but if I change like this, the config works but I don't know why
from tkinter import *
from PIL import Image, ImageTk
def image_resize(size, link):
image = Image.open(link)
image = image.resize(size, Image.ANTIALIAS)
image = ImageTk.PhotoImage(image)
return image
root = Tk()
root.title()
precision = PhotoImage(file="gui_project/item_simulation/precision.png")
rune00 = PhotoImage(file="gui_project/item_simulation/domination.png")
runepage_precision = Button(root, width=20, height=20,\
image=precision, command=select_precision)
runepage_00 = Button(root, width=20, height=20, image=rune00)
# using inside the code
overheal = image_resize((20, 20), "gui_project/item_simulation/overheal.png")
runepage_00.config(image=overheal)
runepage_precision.pack()
runepage_00.pack()
root.mainloop()
to make it short
first was
def select_precision():
overheal = image_resize((20, 20), "gui_project/item_simulation/overheal.png")
runepage_00.config(image=overheal)
runepage_precision = Button(root, width=20, height=20,\
image=precision, command=select_precision)
runepage_00 = Button(root, width=20, height=20, image=rune00)
and second was
runepage_precision = Button(root, width=20, height=20,\
image=precision, command=select_precision)
runepage_00 = Button(root, width=20, height=20, image=rune00)
overheal = image_resize((20, 20), "gui_project/item_simulation/overheal.png")
runepage_00.config(image=overheal)
I have created a widget in python using tkinter library. It has one combobox
from tkinter import *
from tkinter.ttk import *
import os
import time
import win32api
def f_step():
window=Tk()
style = Style()
style.configure('W.TButton', font =
('calibri', 12, 'bold'),
foreground = 'blue')
s = Style() # Creating style element
s.configure('Wild.TRadiobutton', # First argument is the name of style. Needs to end with: .TRadiobutton
background='bisque2', # Setting background to our specified color above
font = "calibri 10 bold") # You can define colors like this also
window.title('Tool tool')
window.geometry("700x300+10+10")
#window.geometry(side="top", fill="both", expand = True)
txt_1=StringVar()
lbl_1 = Label(window,text="Are result files same", background ="bisque2",font = "calibri 10 bold").place(x=10,y=40)
lbl_2 = ttk.Combobox(window,textvariable = txt_1, values = ["Yes","No"], background ="bisque2",font = "calibri 10 bold").place(x=275,y=40)
a1 = txt_1.get()
if a1 == "Yes":
txt_2=StringVar()
lbl_3 = Label(window,text="Working directory path", background ="bisque2",font = "calibri 10 bold").place(x=10,y=70)
txt_b = Entry(window,textvariable=txt_2,width=60).place(x=275,y=70)
txt_3=StringVar()
lbl_4 = Label(window,text="file name (without extenstion)", background ="bisque2",font = "calibri 10 bold").place(x=10,y=100)
txt_c = Entry(window,textvariable=txt_2,width=60).place(x=275,y=100)
elif a1 == "No":
txt_2=StringVar()
lbl_3 = Label(window,text="Working directory path", background ="bisque2",font = "calibri 10 bold").place(x=10,y=70)
txt_b = Entry(window,textvariable=txt_2,width=60).place(x=275,y=70)
txt_3=StringVar()
lbl_4 = Label(window,text="file1 name (without extenstion)", background ="bisque2",font = "calibri 10 bold").place(x=10,y=100)
txt_c = Entry(window,textvariable=txt_2,width=60).place(x=275,y=100)
txt_4=StringVar()
lbl_5 = Label(window,text="file2 name (without extenstion)", background ="bisque2",font = "calibri 10 bold").place(x=10,y=130)
txt_d = Entry(window,textvariable=txt_2,width=60).place(x=275,y=130)
btn_1 = Button(window, text="run",style = 'W.TButton',command=clicked)
btn_1.place(x=300,y=250)
window.configure(bg='bisque2')
window.resizable(0, 0)
window.mainloop()
def clicked():
a=1212
f_step()
It has combobox but once i select one option (yes or no) it does not update the following options. Please help me to solve this as i am not sure how to update the application based on real time inputs. i do not want it to updated once i click the button. Also this is just the portion of code which i am having the problem please advise.
You should bind the virtual event <<ComboboxSelected>> to a callback and show the required labels and entries based on the combobox selection in the callback:
def f_step():
window = Tk()
window.title('Tool tool')
window.geometry("700x300+10+10")
#window.geometry(side="top", fill="both", expand = True)
window.configure(bg='bisque2')
window.resizable(0, 0)
s = ttk.Style() # Creating style element
s.configure('W.TButton', font=('calibri', 12, 'bold'), foreground='blue')
s.configure('Wild.TRadiobutton', # First argument is the name of style. Needs to end with: .TRadiobutton
background='bisque2', # Setting background to our specified color above
font="calibri 10 bold") # You can define colors like this also
def on_change(event):
# show the labels and entries
lbl_3.place(x=10, y=70)
txt_b.place(x=275, y=70)
lbl_4.place(x=10, y=100)
txt_c.place(x=275, y=100)
a1 = txt_1.get()
if a1 == "Yes":
lbl_5.place_forget()
txt_d.place_forget()
else:
lbl_5.place(x=10, y=130)
txt_d.place(x=275, y=130)
txt_1 = StringVar()
Label(window, text="Are result files same", background ="bisque2", font="calibri 10 bold").place(x=10,y=40)
cb_1 = ttk.Combobox(window, textvariable=txt_1, values=["Yes","No"], background="bisque2", font="calibri 10 bold", state="readonly")
cb_1.place(x=275,y=40)
cb_1.bind("<<ComboboxSelected>>", on_change)
# define the labels and entries and initially they are hidden
txt_2 = StringVar()
lbl_3 = Label(window, text="Working directory path", background="bisque2", font="calibri 10 bold")
txt_b = Entry(window, textvariable=txt_2, width=60)
txt_3 = StringVar()
lbl_4 = Label(window, text="file1 name (without extenstion)", background="bisque2", font="calibri 10 bold")
txt_c = Entry(window, textvariable=txt_3, width=60)
txt_4 = StringVar()
lbl_5 = Label(window, text="file2 name (without extenstion)", background="bisque2", font="calibri 10 bold")
txt_d = Entry(window, textvariable=txt_4, width=60)
btn_1 = ttk.Button(window, text="run", style='W.TButton', command=clicked)
btn_1.place(x=300, y=250)
window.mainloop()
Note that your code uses txt_2 variable in txt_c and txt_d entries and I think it is typo and fix it.
what you are looking for is lbl_2.bind("<<ComboboxSelected>>", f_step) also note that you must add a parameter in the f_step function as it is passed form combo virtual event. This will make sure to update whenever the option is changed
Try this:
from tkinter import *
from tkinter.ttk import *
import os
import time
import win32api
def f_step(event=None):
a1 = txt_1.get()
if a1 == "Yes":
txt_2=StringVar()
lbl_3 = Label(window,text="Working directory path", background ="bisque2",font = "calibri 10 bold").place(x=10,y=70)
txt_b = Entry(window,textvariable=txt_2,width=60).place(x=275,y=70)
txt_3=StringVar()
lbl_4 = Label(window,text="file name (without extenstion)", background ="bisque2",font = "calibri 10 bold").place(x=10,y=100)
txt_c = Entry(window,textvariable=txt_2,width=60).place(x=275,y=100)
elif a1 == "No":
txt_2=StringVar()
lbl_3 = Label(window,text="Working directory path", background ="bisque2",font = "calibri 10 bold").place(x=10,y=70)
txt_b = Entry(window,textvariable=txt_2,width=60).place(x=275,y=70)
txt_3=StringVar()
lbl_4 = Label(window,text="file1 name (without extenstion)", background ="bisque2",font = "calibri 10 bold").place(x=10,y=100)
txt_c = Entry(window,textvariable=txt_2,width=60).place(x=275,y=100)
txt_4=StringVar()
lbl_5 = Label(window,text="file2 name (without extenstion)", background ="bisque2",font = "calibri 10 bold").place(x=10,y=130)
txt_d = Entry(window,textvariable=txt_2,width=60).place(x=275,y=130)
def clicked():
a=1212
#f_step()
window=Tk()
style = Style()
style.configure('W.TButton', font =
('calibri', 12, 'bold'),
foreground = 'blue')
s = Style() # Creating style element
s.configure('Wild.TRadiobutton', # First argument is the name of style. Needs to end with: .TRadiobutton
background='bisque2', # Setting background to our specified color above
font = "calibri 10 bold") # You can define colors like this also
window.title('Tool tool')
window.geometry("700x300+10+10")
#window.geometry(side="top", fill="both", expand = True)
txt_1=StringVar()
lbl_1 = Label(window,text="Are result files same", background ="bisque2",font = "calibri 10 bold").place(x=10,y=40)
lbl_2 = Combobox(window,textvariable = txt_1, values = ["Yes","No"], background ="bisque2",font = "calibri 10 bold")
lbl_2.place(x=275,y=40)
#lbl_2.current(1)
lbl_2.bind("<<ComboboxSelected>>", f_step)
btn_1 = Button(window, text="run",style = 'W.TButton',command=clicked)
btn_1.place(x=300,y=250)
window.configure(bg='bisque2')
window.resizable(0, 0)
window.mainloop()
also if you want to update only when run is clicked you may call the f_step from clicked() and remove the binding from combobox.
ok as per your request here is the Updated code:
from tkinter import *
from tkinter.ttk import *
import os
import time
import win32api
def f_step(event=None):
global lbl_3
global txt_b
global lbl_4
global lbl_c
global lbl_5
global txt_d
hide()
a1 = txt_1.get()
txt_2=StringVar()
txt_3=StringVar()
lbl_3 = Label(window,text="Working directory path", background ="bisque2",font = "calibri 10 bold")
lbl_3.place(x=10,y=70)
txt_b = Entry(window,textvariable=txt_2,width=60)
txt_b.place(x=275,y=70)
txt_b = Entry(window,textvariable=txt_2,width=60)
txt_b.place(x=275,y=70)
lbl_4 = Label(window,text="file name (without extenstion)", background ="bisque2",font = "calibri 10 bold")
lbl_4.place(x=10,y=100)
txt_c = Entry(window,textvariable=txt_2,width=60)
txt_c.place(x=275,y=100)
if a1 == "No":
lbl_5 = Label(window,text="file2 name (without extenstion)", background ="bisque2",font = "calibri 10 bold")
lbl_5.place(x=10,y=130)
txt_d = Entry(window,textvariable=txt_2,width=60)
txt_d.place(x=275,y=130)
def hide():
#lbl_3.place_forget()
lbl_3.destroy()
txt_b.destroy()
lbl_4.destroy()
txt_c.destroy()
lbl_5.destroy()
txt_d.destroy()
def clicked():
a=1212
f_step()
window=Tk()
style = Style()
style.configure('W.TButton', font =
('calibri', 12, 'bold'),
foreground = 'blue')
s = Style() # Creating style element
s.configure('Wild.TRadiobutton', # First argument is the name of style. Needs to end with: .TRadiobutton
background='bisque2', # Setting background to our specified color above
font = "calibri 10 bold") # You can define colors like this also
window.title('Tool tool')
window.geometry("700x300+10+10")
lbl_3 = Label(window)
txt_b = Entry(window)
txt_b = Entry(window)
lbl_4 = Label(window)
txt_c = Entry(window)
lbl_5 = Label(window)
txt_d = Entry(window)
txt_1=StringVar()
lbl_1 = Label(window,text="Are result files same", background ="bisque2",font = "calibri 10 bold").place(x=10,y=40)
lbl_2 = Combobox(window,textvariable = txt_1, values = ["Yes","No"], background ="bisque2",font = "calibri 10 bold")
lbl_2.place(x=275,y=40)
#lbl_2.current(1)
lbl_2.bind("<<ComboboxSelected>>", f_step)
btn_1 = Button(window, text="run",style = 'W.TButton',command=clicked)
btn_1.place(x=300,y=250)
window.configure(bg='bisque2')
window.resizable(0, 0)
window.mainloop()
you can use the widget.destroy() to delete the widget whole together or widget.place_forget to temporarily hide the widget. Note: if you use widget.place_forget you don't need to recreate the widget instead change the existing widget using widget.config
First of all, sorry for that vague title. I am making a python application that shows time, fetches weather and News. Now, when i print news through tkinter label, it prints the titles of news on a separate line but in the center. If I try to specify the .pack(side=LEFT) geometry, it goes to the left but all the headlines print in a string and not in a newline. I have tried adding new line by '\n' and even carriage return '\n' but in vain. Please help me out with this issue. Attaching the code below.
P.s i could not get it the news to work with the For loop so i manually printed arrays.
from tkinter import *
import datetime
from PIL import Image, ImageTk
import requests
class Clock(Frame):
def __init__(self, parent):
Frame.__init__(self,parent, bg='black')
self.now = datetime.datetime.today()
self.time = str(self.now.hour) + ":" + str(self.now.minute)
self.timelb = Label(self, text=self.time, font=("Helvetica 50"), bg='black', fg='white')
self.timelb.pack(anchor=NE,padx=60,pady=0)
self.date = str(self.now.day) + '.' + str(self.now.month) + '.' + str(self.now.year)
self.day = self.now.strftime('%A')
self.daylb = Label(self, text=self.day, font="Helvetica 20", bg='black', fg='white')
self.daylb.pack(anchor=NE,padx=60)
self.datelb = Label(self, text=self.date, font="Helvetica 25", bg = 'black', fg='white')
self.datelb.pack(anchor=NE, padx=60)
class Weather(Frame):
def __init__(self, parent):
Frame.__init__(self,parent,bg='black')
url = 'http://api.openweathermap.org/data/2.5/weather?appid=c73d9cdb31fd6a386bee66158b116cd0&q=Karachi&units=metric'
json = requests.get(url).json()
temperature = json['main']['temp']
description = json['weather'][0]['description']
icon_id = json['weather'][0]['icon']
city = 'Karachi'
icon_url = ('http://openweathermap.org/img/wn/{icon}#2x.png'.format(icon=icon_id))
self.im = Image.open(requests.get(icon_url, stream=True).raw)
self.ph = ImageTk.PhotoImage(self.im)
degree = u'\N{DEGREE SIGN}' + 'C'
self.pic_label = Label(self,image=self.ph,bg='black')
self.pic_label.pack()
self.lab= Label(self,text=(str(temperature) + degree),font=("Helvetica 40"), bg='black', fg='white')
self.lab.pack()
self.description_label=Label(self, text=description, font='Helvetica 20',bg='black', fg='white')
self.description_label.pack()
self.city_label=Label(self, text=city, font = 'Helvetica 10', bg='black', fg='white')
self.city_label.pack()
class News(Frame):
def __init__(self, parent):
super(News, self).__init__(bg='black')
url = " https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=caa7f97ce8f2400a9785cbe704afc345"
json = requests.get(url).json()
self.title = 'Headlines'
self.title_lb = Label(self, text=self.title, font='Helvetica 25',bg='black', fg='white')
self.title_lb.pack(side=TOP, anchor=N)
im = Image.open('Newspaper_reduced.png')
self.pho = ImageTk.PhotoImage(im)
news1 = json['articles'][0]['title']
news2 = json['articles'][1]['title']
news3 = json['articles'][2]['title']
news4 = json['articles'][3]['title']
news5 = json['articles'][4]['title']
self.img = Label(self,image=self.pho,bg='black')
self.img.pack(side=LEFT)
self.headline1_lb = Label(self, text=news1, font = 'Helvetica 15' ,bg='black', fg='white')
self.headline1_lb.pack(side=LEFT)
self.img2 = Label(self,image=self.pho,bg='black')
self.img2.pack(side=LEFT)
self.headline2_lb = Label(self, text = news2, font='Helvetica 15',bg='black', fg='white')
self.headline2_lb.pack(side=LEFT)
self.img3 = Label(self,image=self.pho,bg='black')
self.img3.pack(side=LEFT)
self.headlines3_lb = Label(self, text=news3, font='Helvetica 15',bg='black', fg='white')
self.headlines3_lb.pack(side=LEFT)
self.img4 = Label(self,image=self.pho,bg='black')
self.img4.pack(side=LEFT)
self.headlines4_lb = Label(self, text=news4, font='Helvetica 15',bg='black', fg='white')
self.headlines4_lb.pack(side=LEFT)
self.img5 = Label(self,image=self.pho,bg='black')
self.img5.pack(side=LEFT)
self.headlines5_lb = Label(self, text=news5, font='Helvetica 15',bg='black', fg='white')
self.headlines5_lb.pack(side=LEFT)
class Fullscreen:
def __init__(self):
self.tk = Tk()
self.tk.configure(bg='black')
self.tk.title('smartmirror')
self.topFrame = Frame(self.tk , bg='black')
self.topFrame.pack(side=TOP, fill=BOTH, expand=YES)
self.bottomFrame = Frame(self.tk, bg='black')
self.bottomFrame.pack(side=BOTTOM, fill=BOTH, expand=YES)
self.clock = Clock(self.topFrame)
self.clock.pack(side=RIGHT, anchor=NE, padx=50, pady=60)
self.weather = Weather(self.topFrame)
self.weather.pack(side=LEFT, anchor=NW, padx=50, pady=70)
self.news = News(self.bottomFrame)
self.news.pack(side=BOTTOM, anchor=S)
if __name__ == '__main__':
w = Fullscreen()
w.tk.mainloop
First: I removed images in code because I don't have them and I want to waste time to search images which I could use as replacement.
If you set different color for labels then you see then have different width - they use width of text.
If you use
self.headline1_lb.pack(fill='x')
then they will use the same width but text still is in center.
If you use
Label(..., anchor='w')
then it will move text to left side.
If you will put in Label text with many lines then you may need also
Label(..., anchor='w', justify='left')
If you want use full width of window for text then you have to use fill='x'
self.news.pack(side=BOTTOM, anchor='s', fill='x')
After that you can again set black background.
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]
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()