Drawing a png image on a tkinter canvas python - python-3.x

I am trying to create a simple game using tkinter in python 3.5 using the canvas widget. For this game I am need to be able to use a transparent (png) image. Here is my code:
from PIL import ImageTk
from tkinter import Tk, Canvas
root = Tk()
im = ImageTk.PhotoImage(file="test.png")
canvas = Canvas(root, width=900, height=900)
canvas.pack()
canvasImage = canvas.create_image(0, 0, image=im, anchor="nw")
root.mainloop()
The problem is that, despite getting no errors i can't load an image with a transparent background but i can load png images with no transparent background.

You should try this:
from tkinter import *
root = Tk()
canvas = Canvas(root, width=500, height=500)
canvas.pack()
img = PhotoImage(file='path/your_image.png')
canvas.create_image(250, 250, image=img)
root.mainloop()
Output here

Related

How to embed a base64 image into python 3 guizero/tkinter?

I am trying to embed a base64 image into either a box or the picture widget so my application requires less files. I found a way to do it with plain tkinter at Base64 string to image in tkinter answered by Bryan Oakley and I updated the code to work with python 3.
What they did
import tkinter as tk
IMAGE_DATA = '''
R0lGODlhEAAQALMAAAAAAP//AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAA\nAAAAACH5BAEAAAIALAAAAAAQABAAQAQ3UMgpAKC4hm13uJnWgR
TgceZJllw4pd2Xpagq0WfeYrD7\n2i5Yb+aJyVhFHAmnazE/z4tlSq0KIgA7\n
'''
root = tk.Tk()
image = tk.PhotoImage(data=IMAGE_DATA)
label = tk.Label(root, image=image, padx=20, pady=20)
label.pack()
root.mainloop()
What I've tried
import tkinter as tk
from guizero import *
import base64
app= App()
#the same image they used for testing
IMAGE_DATA = '''
R0lGODlhEAAQALMAAAAAAP//AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAA\nAAAAACH5BAEAAAIALAAAAAAQABAAQAQ3UMgpAKC4hm13uJnWgR
TgceZJllw4pd2Xpagq0WfeYrD7\n2i5Yb+aJyVhFHAmnazE/z4tlSq0KIgA7\n
'''
box=Box(app,width=app.width,height=app.height)
box.bg='gray'
#button=PushButton(app, image=IMAGE_DATA)
#image = Picture(box, image=IMAGE_DATA)
#picText = Text(box, tk.data=IMAGE_DATA)
#Pure tkinter
'''
image = tk.PhotoImage(data=IMAGE_DATA)
label = tk.Label(box, image=image, padx=20, pady=20)
label.pack()
'''
app.display()
What I used
https://lawsie.github.io/guizero/ (module)
https://base64.guru/converter/encode/image (converts images to base 64)
The image option requires an instance of the PhotoImage class from tkinter. So, create an instance, and pass that to guizero widget.
image = tk.PhotoImage(data=IMAGE_DATA)
button=PushButton(app, image=image)

I am using tkinter ,I want to clear the canvas using a button(close_button) but the camera is always on and the button not doing anything

I am using Tkinter, I want to clear the canvas using a button(close_button) but the camera is always on and the button not doing anything I want the button to close the camera feed and reset the canvas so that the canvas becomes as it was before I opened the cam
from tkinter import*
import tkinter as tk
from PIL import Image, ImageTk
import cv2
# new window function which will be called when button pressed
class OpenCam():
def __init__(self, window, cap):
self.window = window
self.cap = cap
self.width = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)
self.height = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
self.interval = 20 # Interval in ms to get the latest frame
# Create canvas for image
self.canvas = tk.Canvas(self.window, width=self.width, height=self.height)
self.canvas.place(x=100,y=100)
# close Button need to close cam and reset canvas
close_button = tk.Button(root, text="close", bg='black', fg='white', command=self.canvas.delete() )
close_button.place(x=610,y=0)
# Update image on canvas
self.update_image()
def update_image(self):
# Get the latest frame and convert image format
self.image = cv2.cvtColor(self.cap.read()[1], cv2.COLOR_BGR2RGB) # to RGB
self.image = Image.fromarray(self.image) # to PIL format
self.image = ImageTk.PhotoImage(self.image) # to ImageTk format
# Update image
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.image)
# Repeat every 'interval' ms
self.window.after(self.interval, self.update_image)
def new_window():
OpenCam(root, cv2.VideoCapture(0))
#create original window
root = tk.Tk()
root.title("ADD CAM: ")
canvas = tk.Canvas(root, height=1000, width=1000)
canvas.pack()
#create button that will be placed
button = tk.Button(root, text="ADD CAM", bg='black', fg='white', command=new_window )
button.place(x=0,y=0)
root.mainloop()

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()

RGBA image not showing up with Pillow and tkinter

I am trying to get a PNGA image to show up in my UI using Pillow and Tkinter. I'm on python 3.7.7 on macOS.
import sys
import tkinter as tk
from PIL import ImageTk, Image
path = "path_to_image.png"
im = Image.open(path)
print(im.mode) # prints RGBA
root = tk.Tk()
root.title("Karel")
frame = tk.Frame(root)
frame.pack()
canvas = tk.Canvas(frame, bg="white", width=500, height=500)
canvas.pack()
img = Image.open(path) # PIL solution
img = img.resize((250, 250), Image.ANTIALIAS) #The (250, 250) is (height, width)
img = ImageTk.PhotoImage(img) # convert to PhotoImage
image = canvas.create_image(150,150, image = img)
root.mainloop()
When I try this with images without an alpha channel, it works. Adding img = ImageTk.PhotoImage(img.convert("RGB")) to remove the alpha channel makes a black box appear.
Any help would be greatly appreciated.
The image:
I don't understand what you are trying to do, but the issue is that all the information in your image is in the alpha (i.e. transparency) channel. I can demonstrate that by splitting out the R, G, B and A channels using ImageMagick in the Terminal like this and laying them out beside each other:
magick image.png -channel RGBA -separate -background none +smush 10 result.png
So, the Red, Green and Blue channels are all zero (i.e. black), and the alpha channel has white where it is transparent and you can see through to the RGB black, and it has black where it is transparent.
So, as regards your question, since all the info is in the alpha channel, you could take just the alpha channel as your image:
#!/usr/bin/env python3
import tkinter as tk
from PIL import ImageTk, Image
root = tk.Tk()
root.title("Karel")
frame = tk.Frame(root)
frame.pack()
canvas = tk.Canvas(frame, bg="red", width=500, height=500)
canvas.pack()
path = "image.png"
img = Image.open(path).getchannel('A') # Take just alpha channel
img = img.point(lambda a: 255-a) # Invert black/white
img = img.resize((250, 250), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
image = canvas.create_image(150,150, image = img)
root.mainloop()
Note that you can easily install ImageMagick on macOS with homebrew:
brew install imagemagick
If you work with images, while you are there, get these packages too:
brew install pngcheck exiftool jhead

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()

Resources