size of a background image in tkinter - python-3.x

I need to resize my window(tkinter) according to the width and height of my background image.
My code
from tkinter import *
from PIL import ImageTk
import cv2
image=cv2.imread("New_refImg.png")
width_1, height_1,channels = image.shape
canvas = Canvas(width = width_1, height = height_1, bg = 'blue')
canvas.pack(expand = YES, fill = BOTH)
img = ImageTk.PhotoImage(file = "New_refImg.png")
canvas.create_image(10, 10, image = img, anchor = NW)
mainloop()
I'm using a simple method, I call the same image twice : image=cv2.imread("New_refImg.png") and img = ImageTk.PhotoImage(file = "New_refImg.png") but is there a way change this line img = ImageTk.PhotoImage(file = "New_refImg.png") to something like that img = ImageTk.PhotoImage(image) (image already has been called in the 3rd line of the code)
Thank you

I don't know about PIL, but I can show you how to do it in tkinter:
from tkinter import *
root = Tk() # Create Tk before you can create an image
img = PhotoImage(file='pilner.png')
w, h = img.width(), img.height()
canvas = Canvas(root, width=w, height=h, bg='blue', highlightthickness=0)
canvas.pack(expand = YES, fill = BOTH)
canvas.create_image(0, 0, image=img, anchor=NW)
root.mainloop()
highlightthickness=0 rmoves the highlight border on the canvas. I'm positioning it at 0,0 so as to not show the bg.

Related

Is it possible to make an uploaded photo realtive in tkinter?

As in question is it possible to upload a photo and make it relative?
I am trying to upload an image to my GUI, but it is not relative, so when you maximalize window, then unfortunatelly there is a problem with its size.
I want to change the image size dynamically when the window is resizing
Some example code:
import tkinter as tk
from PIL import ImageTk, Image
HEIGHT, WIDTH = 640, 700
root = tk.Tk()
canvas0 = tk.Canvas(height=HEIGHT, width=WIDTH)
canvas0.pack()
canvas = tk.Canvas(bg='black')
canvas.place(relx=0, rely=0, relheight=1, relwidth=1)
frame = tk.Frame(canvas, bg='#009900')
frame.place(relx=0.12, y=2, rely=0, relwidth=0.75, relheight=1)
column_1_img = Image.open('column.png')
column_1_img = ImageTk.PhotoImage(column_1_img)
column_label_1 = tk.Label(canvas, image=column_1_img)
column_label_1.image = column_1_img
column_label_1.place(relheight=1, relwidth=0.2)
root.mainloop()
This code produces this output:
Not fullscreen
Fullscreen
I want an image to automatically adjust to the label size, so do you have some ideas how?
Bind the <Configure> to an event handler and use the PIL's resize method to resize the image.
Here is an example:
import tkinter as tk
from PIL import ImageTk, Image
def resize_image(event):
column_label_1.resized = ImageTk.PhotoImage(column_1_img.resize((event.width, event.height), resample = Image.NEAREST))
column_label_1['image'] = column_label_1.resized
HEIGHT, WIDTH = 640, 700
root = tk.Tk()
canvas0 = tk.Canvas(height=HEIGHT, width=WIDTH)
canvas0.pack()
canvas = tk.Canvas(bg='black')
canvas.place(relx=0, rely=0, relheight=1, relwidth=1)
frame = tk.Frame(canvas, bg='#009900')
frame.place(relx=0.12, y=2, rely=0, relwidth=0.75, relheight=1)
column_1_img = Image.open(r'img_path')
column_img = ImageTk.PhotoImage(column_1_img)
column_label_1 = tk.Label(canvas, image=column_img)
column_label_1.image = column_1_img
column_label_1.place(relheight=1, relwidth=0.2)
column_label_1.bind('<Configure>', resize_image)
root.mainloop()

I want to display image dynamically in Tkinter using Pillow

I want to be able to display photos dynamically in Tkinter I have one button that will find the paths to the photos I want to display and as I add photos I want them to be displayed at the top of the canvas
I have already tried going through a for loop of the array after I upload the photos but that doesn't seem to do what I want, and now I am trying to iterate with a while loop but that doesn't work. I am kind of at a loss now. Below is my code
import tkinter as tk
from tkinter import filedialog as tkfd
from PIL import ImageTk, Image
import time
photo_name_list = []
def find_photos():
photo = tkfd.askopenfile()
photo_name_list.append(photo.name)
window = tk.Tk()
#creates the canvas
canvas = tk.Canvas(window, width = WINDOW_WIDTH,
height = WINDOW_HEIGHT, bg="green")
canvas.pack()
b1 = tk.Button(canvas, text="Click me to add 5 photos of yourself",
height = 5, width = 30, command = find_photos)
canvas.create_window(WINDOW_WIDTH//3, WINDOW_HEIGHT//3, window = b1)
while True:
if len(photo_name_list) > 0:
for image in photo_name_list:
img = Image.open(image)
tkimage = ImageTk.PhotoImage(img)
tk.Label(window, image=tkimage).pack()
canvas.update()
time.sleep(1/60)
window.mainloop()
So as you can see in the code I have one button that does that takes the path to an image as a string and appends it to the list. I want to display photos as they are appended.
This should work
import tkinter as tk
from tkinter import filedialog as tkfd
from PIL import ImageTk, Image
import time
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
phat_list = []
images_reference_list = []
def find_photos():
photo = tkfd.askopenfile()
file_path = photo.name
img = Image.open(file_path)
photo_image = ImageTk.PhotoImage(img)
tk.Label(window, image=photo_image).pack(side=tk.TOP)
images_reference_list.append(photo_image)
phat_list.append(file_path)
window = tk.Tk()
#creates the canvas
canvas = tk.Canvas(window, width = WINDOW_WIDTH,
height = WINDOW_HEIGHT, bg="green")
canvas.pack(side=tk.BOTTOM)
b1 = tk.Button(canvas, text="Click me to add 5 photos of yourself",
height = 5, width = 30, command = find_photos)
canvas.create_window(WINDOW_WIDTH//3, WINDOW_HEIGHT//3, window = b1)
window.mainloop()
I've added the code lines that display the photo inside the function find_photos().
The while statement was causing some troubles i assume, you have always to check if the while will ever end for have a working code
and if you want to display an image you have always to keep a solid reference of it , the best way is to add it into a list

PNG image that support scaling and changing transparency in python

I want to show PNG picture on canvas.
Before it I need to resize it and change transparency.
I found that I can load image and change alpha channel with PhotoImage like this:
image1 = PIL.Image.open('aqua.png')
image1.putalpha(128)
gif1 = ImageTk.PhotoImage(image1)
Also I can load PhotoImage and resize it like this:
gif1 = PhotoImage(file = 'aqua.png')
gif1 = gif1.subsample(5)
But I can't perform both this things on same PhotoImage
I understand that PhotoImage and ImageTk.PhotoImage are different classes in my code.
>> print (ImageTk.PhotoImage)
<class 'PIL.ImageTk.PhotoImage'>
>> print (PhotoImage)
<class 'tkinter.PhotoImage'>
I tried to found functionality that I need in both classes but without success.
Maybe I need perform subsample and than convert my tkinter.PhotoImage to PIL.ImageTk.PhotoImage and then perform putalpha but it sounds weird.
Please refer me to right direction about png cooking in Python.
Here is all my code:
from tkinter import *
import PIL
from PIL import Image, ImageTk
canvas = Canvas(width = 200, height = 200)
canvas.pack(expand = YES, fill = BOTH)
image1 = PIL.Image.open('aqua.png')
image1.putalpha(128)
gif1 = ImageTk.PhotoImage(image1)
# gif1 = PhotoImage(file = 'aqua.png')
# next line will not work in my case
gif1 = gif1.subsample(5)
canvas.create_image(0, 0, image = gif1, anchor = NW)
mainloop()
You can use the resize method included in the Image class. Here is the modified code:
from tkinter import *
from PIL import Image, ImageTk
canvas = Canvas(width = 200, height = 200)
canvas.pack(expand = YES, fill = BOTH)
image1 = Image.open('aqua.png')
image1.putalpha(128)
image1 = image1.resize((image1.width//5,image1.height//5))
gif1 = ImageTk.PhotoImage(image1)
canvas.create_image(0, 0, image = gif1, anchor = NW)
mainloop()

Removing background from a label in Tkinter

from tkinter import *
from tkinter import messagebox
import tkinter
import hashlib
from PIL import Image, ImageTk
from win32api import GetSystemMetrics
#===========================================================================================
#functions to center windows
def center_window_x(width):
x_coordinate = (GetSystemMetrics(0)/2) - (width/2)
return x_coordinate
def center_window_y(height):
y_coordinate = (GetSystemMetrics(1)/2) - (height/2)
return y_coordinate
#===========================================================================================
#function to create setup page
def first_time_setup(width, height):
setup_window = Tk()
#===========================================================================================
#remove window border and position in center
setup_window.overrideredirect(1)
setup_frame = Frame(setup_window)
setup_frame.pack_propagate(False)
setup_window.geometry('%dx%d+%d+%d' % (width, height, center_window_x(width), center_window_y(height)))
#===========================================================================================
#background image for setup window
canvas = Canvas(setup_window, width=width, height=height)
canvas.grid(columnspan=2)
image = Image.open("setup_background.jpg")
canvas.image = ImageTk.PhotoImage(image)
canvas.create_image(0, 0, image=canvas.image, anchor="nw")
#===================================================================================================
#add username label
start_title = Label(setup_window, text="Username")
start_title.place(x=430,y=225)
#===================================================================================================
#add admin user entry box
admin_user_ent = Entry(setup_window)
admin_user_ent.place(x=500,y=225)
first_time_setup(650, 300)
Is there a way to remove the white background behind the username label? I know how to change the colour of it, but how do I remove it all together.
Is there a way to remove the white background behind the username label? I know how to change the colour of it, but how do I remove it all together.
sorry for posting twice, apparently there wasn't enough text and too much code.
It sounds like you are asking how to make your Label have a transparent background. From my understanding at the moment tkinter does not have this feature for widgets like labels and buttons. However it is still possible to create your own see-through label with Canvas
Here is an example of using Canvas to achieve something similar to what you are looking to do.
import tkinter as tk
root = tk.Tk()
mycanvas = tk.Canvas(root, width = 200, height = 25)
mycanvas.create_rectangle(0, 0, 100, 40, fill = "green")
mycanvas.pack(side = "top", fill = "both", expand = True)
text_canvas = mycanvas.create_text(10, 10, anchor = "nw")
mycanvas.itemconfig(text_canvas, text="Look no background! Thats new!")
root.mainloop()

How can I add text and image inside a frame in Python using tkinter

I am writing my first programming codes. I want to know if I can add text and image label inside a frame. I created a canvas and added two frames to it and then tried to add image and text file (to be displayed at the top of the canvas) but the text and picture do not show. When I run the program without the frames, it does show. Here is the code:
#
from tkinter import *
from tkinter import ttk
root = Tk()
root.title ('iMedic')
canvas = Canvas(root, width = 1600, height = 800)
panewindow = ttk.Panedwindow(canvas, orient = VERTICAL)
panewindow.pack(fill = BOTH, expand = True)
paitents_frame = ttk.Frame(panewindow, width = 1600, height = 400, relief = RAISED)
prescription_frame = ttk.Frame(panewindow, width = 1600, height = 300, relief = RAISED)
panewindow.add(paitents_frame, weight = 1)
panewindow.add(prescription_frame, weight = 1)
canvas.grid(row = 0, column = 0)
photo = PhotoImage(file = './logo.gif')
canvas.create_image(55, 55, image=photo)
canvas.create_text(600, 155, text = 'Welcome', font = ('Helvetica', 72, 'bold'), justify = 'center', fill='blue')
canvas.update
root.mainloop()
#
Is there a way I can fix this? I would assume another way would be to have the pic and text on top and then add frames below it but I don't know how to do it. Thanks!
It's not clear to me why you're adding frames to a canvas but going by the later statement;
I would assume another way would be to have the pic and text on top and then add frames below it but I don't know how to do it.
Here is how you could do it:
Make the panewindow child of root instead of child of canvas
The frames resize to fit their content so I added two labels in each
to make them visible, you should replace those labels with whichever
widgets you need.
I used pack for all the widget placements but you can replace them
with grid and provide the appropriate row and column values.
**
from tkinter import *
from tkinter import ttk
root = Tk()
root.title ('iMedic')
canvas = Canvas(root, width = 1600, height = 250)
canvas.pack(fill = BOTH, expand = True)
photo = PhotoImage(file = './logo.gif')
canvas.create_image(55, 55, image=photo)
canvas.create_text(600, 155, text = 'Welcome', font = ('Helvetica', 72, 'bold'), justify = 'center', fill='blue')
canvas.update
# Make panewindow child of root
panewindow = ttk.Panedwindow(root, orient = VERTICAL)
panewindow.pack(fill = BOTH, expand = True)
# paitents_frame with Labels in it
paitents_frame = ttk.Frame(panewindow, width = 1600, height = 400, relief = RAISED)
paitents_label1 = Label(paitents_frame, text="Name Label")
paitents_label1.pack()
paitents_label2 = Label(paitents_frame, text="Name Label")
paitents_label2.pack()
# prescription_frame with Labels in it
prescription_frame = ttk.Frame(panewindow, width = 1600, height = 300, relief = RAISED)
prescription_label1 = Label(prescription_frame, text="Prescription Text")
prescription_label1.pack()
prescription_label2 = Label(prescription_frame, text="Prescription Text")
prescription_label2.pack()
# Add the frames to panewindow
panewindow.add(paitents_frame, weight = 1)
panewindow.add(prescription_frame, weight = 1)
root.mainloop()
Another option is to leave out the canvas entirely and use labels to place image and text inside a frame. See this post on how to use image in labels
This code demonstrates how to place any text on any image in a Frame.
It works by creating a Label inside the Frame to hold your image and text.
Label requires the compound attribute to be set to either bottom, center, left, right, top or none
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title ('iMedic')
photo = tk.PhotoImage(file = "./logo.gif")
frame = ttk.Frame(root, relief = tk.RAISED)
frame.grid(row = 0, column = 0, sticky = tk.NSEW)
label = tk.Label(
frame, image=photo, compound = tk.CENTER,
font = "Helvetica 40 bold",
foreground = "yellow", text = "Welcome")
label.grid(row = 0, column = 0, sticky = tk.NSEW)
root.mainloop()

Resources