How to update image in tkinter label? - python

I'm a beginner in python so this may be too simple question to ask but i need help..With this code i cannot update image in tkinter label. I can even resize window according to new loaded image's attributes but the new image is not displayed in tkinter label.
from Tkinter import Frame, Tk, Label, Text, Menu, END, BOTH, StringVar
from PIL import ImageTk, Image
import numpy
import tkFileDialog
class DIP(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("DIP Algorithms- Simple Photo Editor")
self.pack(fill=BOTH, expand=1)
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
#Open Image Menu
fileMenu = Menu(menubar)
fileMenu.add_command(label="Open", command=self.onOpen)
menubar.add_cascade(label="File", menu=fileMenu)
#menu for image ngative
basicMenu=Menu(menubar)
basicMenu.add_command(label="Negative", command=self.onNeg)
menubar.add_cascade(label="Basic", menu=basicMenu)
#Image Negative Menu callback
def onNeg(self):
I2=255-self.I;
im = Image.fromarray(numpy.uint8(I2))
photo2=ImageTk.PhotoImage(im)
self.label2= Label(self.parent,border=25,image=photo2)
self.label2.image = photo2 # keep a reference!
self.label2.grid(row=1, column=2)
def setImage(self):
self.img=Image.open(self.fn)
self.I = numpy.asarray(self.img)
l,h = self.img.size
text=str(2*l+100)+"x"+str(h+50)+"+0+0"
self.parent.geometry(text)
photo = ImageTk.PhotoImage(self.img)
self.label1 = Label(self.parent,border=25,image=photo)
self.label1.configure(image=photo)
self.label1.image = photo # keep a reference!
self.label1.grid(row=1, column=1)
#Open Callback
def onOpen(self):
ftypes = [('Image Files', '*.tif *.jpg *.png')]
dlg = tkFileDialog.Open(self, filetypes = ftypes)
filename = dlg.show()
self.fn=filename
#print self.fn #prints filename with path here
self.setImage()
#def onError(self):
#box.showerror("Error", "Could not open file")
def main():
root = Tk()
DIP(root)
root.geometry("320x240")
root.mainloop()
if __name__ == '__main__':
main()
When i run this code, and open an image , it is displayed in label1. But when i open another image again, i' expecting it to be displayed in same label1, but it's not happening. I know the 2nd image is loaded because the window size resized accordingly, the only problem is that it's not being displayed and i cannot figure out why!.

Instead of creating an new tk.Label each time setImage is called, just create it once outside of setImage -- for example, in initUI.
You can then change the image by calling self.label.configure:
import Tkinter as tk
import Image
import ImageTk
import numpy as np
import tkFileDialog
class DIP(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("DIP Algorithms- Simple Photo Editor")
self.pack(fill = tk.BOTH, expand = 1)
menubar = tk.Menu(self.parent)
self.parent.config(menu = menubar)
self.label1 = tk.Label(self, border = 25)
self.label2 = tk.Label(self, border = 25)
self.label1.grid(row = 1, column = 1)
self.label2.grid(row = 1, column = 2)
#Open Image Menu
fileMenu = tk.Menu(menubar)
fileMenu.add_command(label = "Open", command = self.onOpen)
menubar.add_cascade(label = "File", menu = fileMenu)
#menu for image ngative
basicMenu = tk.Menu(menubar)
basicMenu.add_command(label = "Negative", command = self.onNeg)
menubar.add_cascade(label = "Basic", menu = basicMenu)
def onNeg(self):
#Image Negative Menu callback
I2 = 255-self.I;
im = Image.fromarray(np.uint8(I2))
photo2 = ImageTk.PhotoImage(im)
self.label2.image = photo2 # keep a reference!
def setImage(self):
self.img = Image.open(self.fn)
self.I = np.asarray(self.img)
l, h = self.img.size
text = str(2*l+100)+"x"+str(h+50)+"+0+0"
self.parent.geometry(text)
photo = ImageTk.PhotoImage(self.img)
self.label1.configure(image = photo)
self.label1.image = photo # keep a reference!
def onOpen(self):
#Open Callback
ftypes = [('Image Files', '*.tif *.jpg *.png')]
dlg = tkFileDialog.Open(self, filetypes = ftypes)
filename = dlg.show()
self.fn = filename
#print self.fn #prints filename with path here
self.setImage()
#def onError(self):
#box.showerror("Error", "Could not open file")
def main():
root = tk.Tk()
DIP(root)
root.geometry("320x240")
root.mainloop()
if __name__ == '__main__':
main()

Related

Why the image didn't come out in python?

I try to add image in tkinter but it didn't show up but when I added label of text,the text show but the image didn't.Thank you
from tkinter import *
class window1:
def __init__(self, parent, word, geometry):
# image
bank_img = PhotoImage(file='C:\\Users\\user\\PycharmProjects\\pythonProject3\\bank-988164_640.png')
self.parent = parent
self.word = word
self.geometry = geometry
parent.geometry(geometry)
parent.title(self.word)
# Label
label = Label(parent, text="Welcome to the bank", height=3).pack()
bank_logo = Label(parent,image=bank_img).pack()
root = Tk()
app = window1(root, 'beginner bank system', '300x300')
Add root.mainloop() at the end.
root = Tk()
app = window1(root, 'beginner bank system', '300x300')
root.mainloop()

How to print results iteratively on a canvas or text widget within a GUI made in Python?

I have made a simple GUI that has two buttons for a Square function and Exit button. I want to print the results on the canvas as shown in the expected results.
Here are my codes
from tkinter import *
from PIL import Image,ImageTk
from tkinter import filedialog
from PIL import Image, ImageTk
import os
import cv2
import numpy as np
import time
class application(Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.minsize(width=300,height=500)
self.initialize()
def initialize(self):
self.grid_columnconfigure(0,weight=1)
self.grid_columnconfigure(1,weight=1)
self.grid_columnconfigure(2,weight=1)
#Button widgets
###########################################################################################
self.button1 = Button(self,text='Square',bg= 'blue',width=15,height=2, command =Square)
self.button1.grid(column=0,row=1,sticky='W',pady=5)
self.button3 = Button(self,text='Exit',bg= 'blue',width=10,height=2,command=self.destroy)
self.button3.grid(column=1,row=5,sticky='W',pady=5)
#Text widget for inserting the result
############################################################################################
self.canvas = Canvas(self,width=230,height=180,state=NORMAL)
self.canvas.grid(column=0,row=4,sticky='W',padx=100,pady=10)
#self.canvas.configure(bg='green')
#Label widget
############################################################################################
self.label3 = Label(self,text="Square",bg = 'red',width=10,height=2,anchor="center")
self.label3.grid(column=0,row=3,sticky='W',padx=120)
def Square(self):
for i in range(1,10):
y = i**2
print(i, y)
if __name__ == "__main__":
app = application(None)
#font.nametofont('TkDefaultFont').configure(size=10)
app['bg']='red'
app.title("square")
app.mainloop()
My expected results are given in the image below
Not entirely sure what you are asking. But, if you just want to create text on canvas use canvas.create_text(x, y, text).
from tkinter import *
from PIL import Image,ImageTk
class application(Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.minsize(width=300,height=500)
self.initialize()
def initialize(self):
self.grid_columnconfigure(0,weight=1)
self.grid_columnconfigure(1,weight=1)
self.grid_columnconfigure(2,weight=1)
#Button widgets
###########################################################################################
self.button1 = Button(self,text='Square',bg= 'blue',width=15,height=2, command=self.Square)
self.button1.grid(column=0,row=1,sticky='W',pady=5)
self.button3 = Button(self,text='Exit',bg= 'blue',width=10,height=2,command=self.destroy)
self.button3.grid(column=1,row=5,sticky='W',pady=5)
#Text widget for inserting the result
############################################################################################
self.canvas = Canvas(self,width=230,height=180,state=NORMAL)
self.canvas.grid(column=0,row=4,sticky='W',padx=100,pady=10)
#self.canvas.configure(bg='green')
self.label3 = Label(self,text="Square",bg = 'red',width=10,height=2,anchor="center")
self.label3.grid(column=0,row=3,sticky='W',padx=120)
def Square(self):
for i in range(1,10):
y = i**2
print(i, y)
c_id = self.canvas.create_text(0, 20, text=f"{i}\t{y}", fill="blue", font="Times 14")
bbox = self.canvas.bbox(c_id)
self.canvas.coords(c_id, 100, bbox[3]*i)
if __name__ == "__main__":
app = application(None)
#font.nametofont('TkDefaultFont').configure(size=10)
app['bg']='red'
app.title("square")
app.mainloop()

How to display image with upload button in and resize it with window resize (Dynamically)with Tkinter python, I need to add upload button

I need to add upload button so that I can upload the picture and display with this class. Everything working but when I am adding the upload button its giving me some error and my code is not wokring.
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
class Layout:
def __init__(self,master):
self.master = master
self.rootgeometry()
self.canvas = tk.Canvas(self.master)
self.canvas.pack()
self.background_image = Image.open(self.openfn())
self.image_copy = self.background_image.copy()
self.background = ImageTk.PhotoImage(self.background_image)
self.loadbackground()
def loadbackground(self):
self.label = tk.Label(self.canvas, image = self.background)
self.label.bind('<Configure>',self.resizeimage)
self.label.pack(fill='both', expand='yes')
def openfn(self):
filename = filedialog.askopenfilename(title='open')
return filename
def rootgeometry(self):
x=int(self.master.winfo_screenwidth()*0.7)
y=int(self.master.winfo_screenheight()*0.7)
z = str(x) +'x'+str(y)
self.master.geometry(z)
def resizeimage(self,event):
image = self.image_copy.resize((self.master.winfo_width(),self.master.winfo_height()))
self.image1 = ImageTk.PhotoImage(image)
self.label.config(image = self.image1)
root = tk.Tk()
a = Layout(root)
root.mainloop()
Create the Button widget within the class constructor and bind it with self.loadbackground. Also, you don't need to recreate the Label widget every time instead use label.configure(image=yourimage).
Here is the code:
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
class Layout:
def __init__(self,master):
self.master = master
self.rootgeometry()
self.button = Button(self.master, text='Upload', command=self.loadbackground)
self.button.pack()
self.canvas = tk.Canvas(self.master)
self.canvas.pack(fill=BOTH, expand=True)
self.background_image = None
self.image_copy = None
self.background = None
self.label = tk.Label(self.canvas)
self.label.pack(fill='both', expand=True)
def loadbackground(self):
self.background_image = Image.open(self.openfn())
self.image_copy = self.background_image.copy()
self.background = ImageTk.PhotoImage(self.background_image.resize((self.canvas.winfo_width(), self.canvas.winfo_height())))
self.label.configure(image=self.background)
self.label.bind('<Configure>',self.resizeimage)
def openfn(self):
filename = filedialog.askopenfilename(title='open')
return filename
def rootgeometry(self):
x=int(self.master.winfo_screenwidth()*0.7)
y=int(self.master.winfo_screenheight()*0.7)
z = str(x) +'x'+str(y)
self.master.geometry(z)
def resizeimage(self,event):
image = self.image_copy.resize((event.width, event.height))
self.image1 = ImageTk.PhotoImage(image)
self.label.config(image = self.image1)
root = tk.Tk()
a = Layout(root)
root.mainloop()

How can I connect cv2.imread with tkinter?

My plan is to provide a simple interface for the user to select an image. This is then used to perform an analysis.
The problem I have is this:
I can't get the connection between the GUI and the input of the rest of the code. CV2.imread only works when I directly specify the filename.
What is the best way to solve this problem?
Here is the code I am using:
import cv2
import numpy as np
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
from tkinter import ttk
class Root (Tk):
def __init__(self):
super(Root, self).__init__()
self.title("Tkinter First Window")
self.minsize(600,300)
self.labelFrame = ttk.LabelFrame(self, text = "Open a File")
self.labelFrame.grid()
self.button()
def button(self):
self.button = ttk.Button(self.labelFrame, text = "Browse a File", command = self.fileDialog)
self.button.grid()
def fileDialog(self):
self.filename = filedialog.askopenfilename(initialdir = "C:\Python\Code\venv\Testbilder", title ="Select a File", filetype =(("jpeg", "*.jpg"), ("All Files", "*.*")))
self.label = ttk.Label(self.labelFrame, text = "")
self.label.grid()
self.label.configure(text = self.filename)
def main():
show_image = False
**image = cv2.imread("Testbild 3%.jpg")** **I need the connection here! This needs to be the input
blue_pixels_mask = cv2.inRange( from the GUI selection**
cv2.cvtColor(image, cv2.COLOR_BGR2HSV),
np.array([100, 50, 50]),
np.array([130, 255, 255]),
)
total_pixel_count = image.size // 3
if show_image:
cv2.imshow("Image", image)
cv2.imshow("Mask", blue_pixels_mask)
blue_pixel_count = cv2.countNonZero(blue_pixels_mask)
blue_ratio = blue_pixel_count / total_pixel_count
print(f"Das gesamte Bild besteht aus{total_pixel_count} Pixeln.")
print(f"Das Bild beinhaltet {blue_pixel_count} blaue Pixel.")
print(f"Der Blauanteil betrÃĪgt damit: {blue_ratio:0.2%}.")
if show_image:
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
root =Root()
root.mainloop()

Why doesn't my tkinter window show my panel?

I've got the following code:
import tkinter
import cv2
from PIL import Image, ImageTk
import threading
class HudGui:
def __init__(self, window):
# defining everything for video capture and the tkinter window
self.CapDev= cv2.VideoCapture(0)
self.cams = []
self.counter = 0
self.frame = None
self.panel = None
self.wind = window
btn = tkinter.Button(window, text="Snapshot!")
btn.pack(side="bottom", fill="both", expand="yes", padx=10, pady=10)
# defining threading for video stream
self.stopEvent = threading.Event()
self.thread = threading.Thread(target=self.videoLoop(), args=(1,))
self.thread.start()
def videoLoop(self):
while not self.stopEvent.is_set():
# reading and modifying the frame to have the proper data type
self.frame = self.CapDev.read()[1]
image = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)
image = Image.fromarray(image)
image = ImageTk.PhotoImage(image)
if self.panel is None:
self.panel = tkinter.Label(image=image)
self.panel.image = image
self.panel.pack(side="left") # side="left", padx=10, pady=10
# otherwise, update the panel
else:
self.panel.configure(image=image)
self.panel.image = image
hud = tkinter.Tk()
hud.title("HUD")
HudGui(hud)
hud.mainloop()
When I run this code, nothing happens. I get no window but I do know it is updating the panel (I've tested it with printing messages). Could there be permissions problem for accessing the camera and things like that?
Project info:
Python = 3.7.3
opencv-contrib-python = 3.4.4.19

Categories

Resources