Image size increases after zooming in and zooming out - python

Hi All I have a frame with a canvas within the frame which I am using to display an image. I have a scale configured for zooming-in and zooming-out the image. However, I realized that when I zoom-in the image and zoom-out, the image size increases. I am not sure why that's happening. Any suggestion to correct this is welcomed. Thanks. Below is my sample code for demonstration.
frame = tk.Frame(root, width=480, height=450)
frame.place(x=2, y=287)
canvas = tk.Canvas(frame, bg="gray80", bd=1, height=400, width=470)
canvas.pack()
def Create_Image():
global img, Img, canv_img, button
Img = Image.open('.\\image.png')
img = ImageTk.PhotoImage(Img.resize((420, 390), Image.ANTIALIAS))
canv_img = canvas.create_image(235, 207, image=img, anchor=CENTER)
def zoom_img(zoom):
global img
newsize = (Img.size[0]* int(zoom),
Img.size[1]*int(zoom))
scaledimg = Img.resize(newsize, Image.LINEAR)
img = ImageTk.PhotoImage(scaledimg)
canvas.itemconfig(canv_img, image=img)
var = StringVar()
img_scale = tk.Scale(root, variable=var, orient='horizontal', bd=1,
from_=1, to=5, length=200, resolution=1, command=zoom_img)
img_scale.place(x=120, y=140)
def show_image():
Create_Image()
button = tk.Button(root, width=220, height=25, command=show_image)
receive_button.place(x=130, y=50)

Related

_tkinter.TclError: couldn't recognize data in image file PLEASE Solve For Windows 10

I have tried using a formatted code that already existed where I imported 'PIL' from 'ImageTk' however, that has not worked. The image and script is in the same file directory yet the image data is not recognizable. I changed the string to 'raw string' by adding the 'r' in front of the file path and I even tried using a different image and it still outputs the same error. This line linebackground_image = tk.PhotoImage(file=r'C:\Users\kevan\OneDrive\Desktop\Programming for me\Python\Tkinker\bgfortest.png') of the code is the source of error.
Your help would be appreciated
import tkinter as tk
HEIGHT = 700
WIDTH = 800
root = tk.Tk()
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
background_image = tk.PhotoImage(file=r'C:\Users\kevan\OneDrive\Desktop\Programming for me\Python\Tkinker\bgfortest.png')
background_label = tk.Label(root, image=background_image)
background_label.place(x=0, y=0, relheight=1, relwidth=1)
frame = tk.Frame(root, bg='#80c1ff', bd=5)
frame.place(relx=0.5, rely=0.1, relheight=0.1, relwidth=0.75, anchor='n')
button = tk.Button(frame, text="Hello", font=40)
button.place(relx=0.7, relheight=1, relwidth=0.3)
entry = tk.Entry(frame, bg='white', font=40)
entry.place(relheight=1, relwidth=0.65)
lower_frame = tk.Frame(root, bg='#80c1ff', bd=10)
lower_frame.place(relx=0.5, rely=0.25, relheight=0.6, relwidth=0.75, anchor='n')
label = tk.Label(lower_frame, text="This is a python GUI.", bg='cadet blue', fg="Black")
label.place(relwidth=1, relheight=1)
root.mainloop()

how do I display in Tkinter canvas

I'm new to python GUI and I'm going to display my result but I have some problem with displaying it.
I put the whole code but I have a problem with the def blur(file_path) function. here is my code :
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
import cv2 as cv
# =================================== statics and configuration ===================================
color = '#20536C'
root = Tk()
root.title('Opticdisk and Macula detector')
root.configure(bg= color)
root.geometry('1070x700')
root.resizable(width=False, height=False)
root.iconbitmap('J:\Projects\Bachelor Project\download.ico')
filename_path = {}
# =================================== Frames ===================================
top = Frame(root, width=1070, height=70,pady = 9, bg=color)
top.pack(side=TOP)
# top.grid(row = 0 , column= 1)
left = Frame(root, width=750, height=630, bg=color)
left.pack(side=LEFT)
# left.grid(row = 1 , column= 1)
right = Frame(root, width=320, height=630, bg="red")
right.pack(side=LEFT)
# =================================== functions and body ===================================
img1 = ImageTk.PhotoImage(Image.open('J:/Projects/Bachelor Project/eye.ico'))
def open_image(file_path):
file_path['image'] = filedialog.askopenfilename(initialdir="J://uni//final project//Data set",
title="select an image",
filetypes=(('all files', '*.*'), ('jpg files', '*.jpg'), ('tif file','*.tif')))
mainImage = ImageTk.PhotoImage(Image.open(filename_path['image']))
lbl = Label(left, image=mainImage,
width= 749,
height=630,
bg='#020101')#.place(x=20, y=0)
lbl.image = mainImage # keep a reference! to show the image
lbl.place(x=0, y=0)
def blur(file_path):
# messagebox = Message(left).place(x=20,y=10)
try:
Im = cv.imread(file_path['image'])
I = cv.medianBlur(Im,15)
I = cv.resize(I, (300, 300))
canvas = Canvas(left, width=749, height=630)
# canvas.place(x=0, y=0)
# canvas.pack()
# canvas.create_image(20, 20, anchor=NW, image=I)
# canvas.image = I
canvas.pack()
cv.imshow('result', I)
cv.waitKey()
except:
print('error')
# =================================== Buttons ===================================
btnBrowse = Button(top, width=93,
text='select file',
fg='#58859a',
font=('Times', 15, 'italic', 'bold'),
bg='#03283a',
command = lambda :open_image(filename_path))
btnBrowse.pack(side=BOTTOM)
btnMask = Button(right, text='Opticdisk',
fg= '#58859a',
font=('Times', 20, 'italic', 'bold'),
bg="#03283a",
width=19,
height=6,
command=lambda: blur(filename_path))
btnMask.pack(side=TOP)
btnMakula = Button(right, text='Makula',
fg= '#58859a',
font=('Times', 20, 'italic', 'bold'),
bg="#03283a",
width=19,
height=6)
btnMakula.pack(side=TOP)
btnClear = Button(right, text='exit',
fg= '#58859a',
font=('Times', 20, 'italic', 'bold'),
bg="#03283a",
width=19,
height=6,
command=root.quit)
btnClear.pack(side=TOP)
root.mainloop()
I'm going to display I. As you can see in the comments I try canvas but it shows nothing but a white screen
OpenCV library shows the picture I with no problem as I want in the line cv.imshow('result', I) but I want to display it inside the program.
I would be appreciated if you guys help me?
as I'm in a hurry I found a solution for my above problem
I just save the resulting photo I and then put the address of the file in a dictionary path['image'] and open it with the same way we open folders in function open_image(file_path) here is my solution :
def blur(file_path):
path={}
# messagebox = Message(left).place(x=20,y=10)
try:
Im = cv.imread(file_path['image'])
I = cv.medianBlur(Im,15)
I = cv.resize(I, (300, 300))
# here is the solution
cv.imwrite('J://uni//final project//res_image//finalresult.jpg',I)
path['image'] = ('J://uni//final project//res_image//finalresult.jpg')
mainImage = ImageTk.PhotoImage(Image.open(path['image']))
lbl = Label(left, image=mainImage,
width=749,
height=630,
bg='#020101') # .place(x=20, y=0)
lbl.image = mainImage # keep a reference! to show the image
lbl.place(x=0, y=0)
#cv.imshow('result', I)
#cv.waitKey()
except:
print('error')

How to resize image using canvas frame in python

Here I am trying to display images using the canvas frame but it is not showing anything.
what is wrong in this.
when I replace the frame with root in Label widget it is working.
Thanks
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
import tkinter as tk
root = Tk()
root.title("Title")
root.geometry('600x600')
def resize_image(event):
new_width = event.width
new_height = event.height
image = copy_of_image.resize((new_width, new_height))
photo = ImageTk.PhotoImage(image)
label.config(image = photo)
label.image = photo
def on_configure(event):
canvas.configure(scrollregion=canvas.bbox('all'))
scrollbary = Scrollbar(root, orient = tk.VERTICAL)
scrollbarx = Scrollbar(root,orient = tk.HORIZONTAL)
canvas = tk.Canvas(root,yscrollcommand = scrollbary.set,
xscrollcommand = scrollbarx.set)
scrollbary.config(command=canvas.yview)
scrollbarx.config(command=canvas.xview)
scrollbary.pack(side=tk.RIGHT, fill='y',expand = tk.FALSE)
scrollbarx.pack(side=tk.BOTTOM,fill = 'x',expand = tk.FALSE)
canvas.pack(side=tk.LEFT, padx=5, pady=5,
fill=tk.BOTH, expand=tk.TRUE)
canvas.bind('<Configure>', on_configure)
frame = tk.Frame(canvas)
canvas.create_window((0,0), window=frame, anchor='nw')
image = Image.open('logo1.png')
copy_of_image = image.copy()
photo = ImageTk.PhotoImage(image)
label = ttk.Label(frame, image = photo)
label.bind('<Configure>', resize_image)
label.pack(fill=BOTH, expand = YES)
root.mainloop()

Expanding the background image to fit window and stacking the frames over it in tkinter

I am trying to add a background image to my GUI app using tkinter. In the root window, I have two frames, named container_1 and container_2. When I am adding the background image, these framed are pushed outside the image. I can see them as the window size is higher than image size. If it is less, it isn't even visible. How can I make them place over the background image? Is it possible to give different background images for container_1 and container_2?
ans suggestions please.
(imgae in the comment link)
import tkinter as tk
def FnToShow():
container_2.pack(side="right",expand=True, fill="x", padx=1, pady=1)
def FnToHide():
container_2.pack_forget()
root = tk.Tk()
root.geometry('800x600')
#bg image
background_image=tk.PhotoImage(file= "bgPic.png")
background_label = tk.Label(root, image=background_image)
background_label.pack() # is pack problematic here?
container_1 = tk.Frame(root, borderwidth=2, relief="solid")
container_2 = tk.Frame(root, borderwidth=2, relief="solid")
settingBtn = tk.Button(container_1, text="Settings", command= FnToShow)
settingBtn.grid(row=6, column=4)
setting_1 = tk.Label(container_2, text="Setting-1", fg='#000000')
setting_1.grid(row=3, column=10)
setting_2 = tk.Label(container_2, text="Setting-2", fg='#000000')
setting_2.grid(row=4, column=10)
closeSettingBtn = tk.Button(container_2, text="close Settings", command= FnToHide)
closeSettingBtn.grid(row=5, column=10)
container_1.pack(side="left", expand=True, fill="x", padx=1, pady=1)
root.mainloop()
#setting background image
background_main_img=tk.PhotoImage(file= "bgMain.png")
background_main = tk.Label(root, image=background_main_img)
background_main.place(relx=.5, rely=.5, anchor="center")
#setting background image for container frame
background_con_1=tk.PhotoImage(file= "bgContainer.png")
background_label = tk.Label(container_1, image=background_con_1)
background_label.place(relx=.5, rely=.5, anchor="center")

trying to load image in TKinter but get white space where it should be any ideas?

i only get one picture at the bottom but theres supposed to be 10 all in a vertical tower any idea? also was wondering if the tkinter scrollbar command could have images inside it if not is there any other way to have a scrollbar for lables?
def show_data(self):
print('------------------------------------------------------------------------')
print('data OK')
for i in range(10):
self.image = Image.open(self.data[i][7] + '.jpg')
self.photo = ImageTk.PhotoImage(self.image)
#result0 = Label(self.frame, text=self.data[i][0])
#result0.grid(row=i+3, column=1, sticky=W)
#result1 = Label(self.frame, text=self.data[i][1])
#result1.grid(row=i+3, column=2, sticky=W)
#result2 = Label(self.frame, text=self.data[i][2])
#result2.grid(row=i+3, column=3, sticky=W)
#result3 = Label(self.frame, text=self.data[i][3])
#result3.grid(row=i+3, column=4, sticky=W)
#result4 = Label(self.frame, text=self.data[i][4])
#result4.grid(row=i+3, column=5, sticky=W)
#result5 = Label(self.frame, text=self.data[i][5])
#result5.grid(row=i+3, column=6, sticky=W)
#result6 = Label(self.frame, text=self.data[i][6])
#result6.grid(row=i+3, column=7, sticky=W)
result7 = Label(self.frame, image=self.photo)
result7.grid(row=i + 3, column=8, sticky=W)
In order to keep the image used in label from being destroyed, you need to keep a reference to the image:
def show_data(self):
print('------------------------------------------------------------------------')
print('data OK')
for i in range(10):
photo = ImageTk.PhotoImage(file=self.data[i][7]+'.jpg')
result7 = Label(self.frame, image=photo)
result7.image = photo # keep a reference of the image
result7.grid(row=i + 3, column=8, sticky=W)
To have a scrollbar for the labels inside a frame, the most common way is to put the frame inside a canvas and then create a scrollbar to scroll the view region of the canvas:
# create a canvas and put it as the left side of window
canvas = Canvas(self.master, width=200, height=600) # assume self.master is Tk()
canvas.pack(side='left')
# create an vertical scrollbar and put it at the right side of window
scrollbar = Scrollbar(self.master, orient='vertical', command=canvas.yview)
scrollbar.pack(side='right', fill='y')
# configure the scrollbar to scroll the canvas in vertical direction
canvas.configure(yscrollcommand=scrollbar.set)
# create the frame as child of canvas to hold the labels
self.frame = Frame(canvas)
canvas.create_window((0,0), window=self.frame, anchor='nw')
# make sure to update the scrolling region if the frame is resized
self.frame.bind('<Configure>', lambda e: canvas.configure(scrollregion=canvas.bbox('all')))

Categories