Tkinter: Adding Image with transparent background to Button - python

hope you're all doing well. I've got a problem I hope you can help with.
I'm trying to build a board game in tkinter. This will have different shaped tiles being placed in squares on top of a background image. I have managed to add in the background with tk.PhotoImage and tk.Label, and correctly resized the image of the tile with ImageTk.PhotoImage.
However, when I place the tile on the board, all transparency is lost and replaced with monotone grey.
Minimal Code:
from PIL import Image,ImageTk
import tkinter as tk
def tile_push():
pass
# Create background image
root = tk.Tk()
root.geometry("390x500") # Size of background board
background_image = tk.PhotoImage(file="Gameboard.png")
background_label = tk.Label(root, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
# Create button
im = Image.open("Chick.png").resize((100,100))
image_player_1 = ImageTk.PhotoImage(im)
b = tk.Button(root, image=image_player_1, command=tile_push, borderwidth=0, highlightthickness=0)
b.place(x=140, y=258, width=115, height=115)
tk.mainloop()
A similar question on SO shows how to set the background as black, but I need the background to be transparent.
Any help will be greatly appreciated!

Thanks for the support acw, I've managed to get it going now. This is what I did:
from PIL import Image,ImageTk
import tkinter as tk
def tile_push(*args, **kwargs):
print("It's alive!")
# Create background image
root = tk.Tk()
root.geometry("390x500") # Size of background board
canvas = tk.Canvas(root, width=390, height=500)
canvas.place(x=0,y=0)
background_image = tk.PhotoImage(file="Gameboard.png")
canvas.create_image((0,0), anchor="nw", image=background_image)
# Create button
im = Image.open("Chick.png").resize((115,115))
imTk = ImageTk.PhotoImage(im)
chick = canvas.create_image((140,258), anchor="nw", image=imTk)
canvas.tag_bind(chick, '<Button-1>', tile_push)
tk.mainloop()

Related

How do I keep this image in the center of the window?

I'm making a hangman-like game; for that, I need all the different stages of the man to be visualized, hence images. I want the entire tkinter window to be an image, when I change the size it pushes the image right.
from tkinter import *
root=Tk()
root.geometry("600x350")
canvas = Canvas(root, width=1600, height=900)
canvas.pack()
img = PhotoImage(file="4.png")
canvas.create_image(470,190, image=img, )
root.mainloop()
If canvas is bigger than window then when you resize then it show more canvas but and it can looks like it moves image.
But if you use smaller canvas then pack() will try to keep centered horizontally. And if you add pack(expand=True) then it will try to keep it centered vertically.
In example code I added red background to window to show where is canvas
import tkinter as tk # PEP8: import *
root = tk.Tk()
root.geometry("600x350")
root['bg'] = 'red'
img = tk.PhotoImage(file="lenna.png")
canvas = tk.Canvas(root, width=600, height=350)
canvas.pack(expand=True)
canvas.create_image(300, 175, image=img)
root.mainloop()
Image Lenna from Wikipedia
PEP 8 -- Style Guide for Python Code
Before resizing:
After resizing:
If you want to draw only image then you could use Label(image=img)
import tkinter as tk # PEP8: import *
root = tk.Tk()
root.geometry("600x350")
root['bg'] = 'red'
img = tk.PhotoImage(file="lenna.png")
label = tk.Label(root, image=img)
label.pack(expand=True)
root.mainloop()
Before resizing:
After resizing:
BTW:
tkinter can bind() some function to event <Configure> and it will execute this function everytime when you resize window (and/or move window) - and this function may also move or resize image in window.
import tkinter as tk # PEP8: import *
from PIL import Image, ImageTk
def resize(event):
global img
lower = min(event.width, event.height)
#print(event.width, event.height, 'lower:', lower)
new_image = original_image.resize((lower, lower))
img = ImageTk.PhotoImage(new_image) # need to assign to global variable because there is bug in PhotoImage
label['image'] = img
# --- main ---
root = tk.Tk()
root.geometry("350x350")
root['bg'] = 'red'
original_image = Image.open("lenna.png")
img = ImageTk.PhotoImage(original_image)
label = tk.Label(root, image=img)
label.pack(expand=True)
root.bind('<Configure>', resize)
root.mainloop()
Before (it resized image at start to fit window):
After (it resized image to fit window):

How do I make a clickable image that gives me the coordinates of the click?

I am trying to make a slideshow-like program using the tkinter module. Here is what I have done:
from tkinter import *
root = Tk()
photo = PhotoImage(file = "image.jpeg")
w = Label(root, image=photo)
w.pack()
def callback(event):
print ("clicked at", event.x, event.y)
##canvas= Canvas(root, width=800, height=500)
canvas= Canvas(root)
canvas.bind("<Button-1>", callback)
canvas.pack()
root.mainloop()
what's going on:
I am putting a picture on the canvas.
I am also detecting left clicks and getting the coordinates (which are printed on the shell)
But what really happens:
The picture (which needs to be in the same folder as the script, btw) appears on top, and a little blank space appears underneath, and I can click that (and get coordinates for the click). If I click the picture, nothing happens. When I click the blank space, it only gives the coordinates of the click for the blank space, not counting the picture as part of the area. If I enlarge the window, it just adds inert blank space on the sides, that do not react to being clicked.
My question is, how do I get the picture to be the clickable part (meaning, gets coordinates as well), and remove the blank space
If you can get the picture to enlarge with the window, that's even better.
Python 3.7.3, on MacBook. I only have the standard library.
You don't need the canvas and should bind on the label instead. Note that tkinter.PhotoImage() does not support JPEG image, use PNG or use Pillow module instead.
from tkinter import *
from PIL import ImageTk
root = Tk()
photo = ImageTk.PhotoImage(file="image.jpeg")
w = Label(root, image=photo)
w.pack()
def callback(event):
print ("clicked at", event.x, event.y)
w.bind("<Button-1>", callback)
root.mainloop()
You are not actually placing the image on the canvas. To place the image on the canvas use
.create_image(). To resize the image to the canvas. you can use resize method provided by the PIL library.
from tkinter import *
from PIL import ImageTk, Image
def resize_event(event):
resized = ImageTk.PhotoImage(img.resize((event.width, event.height), resample = Image.NEAREST))
canvas.itemconfig(img_item, image=resized)
canvas.moveto(img_item, 0, 0)
canvas.image = resized
def callback(event):
print ("clicked at", event.x, event.y)
root = Tk()
img = Image.open(r"Imagepath")
photo = ImageTk.PhotoImage(img)
#w = Label(root, image=photo)
#w.pack()
##canvas= Canvas(root, width=800, height=500)
canvas= Canvas(root)
img_item = canvas.create_image(0, 0, image = photo)
canvas.bind("<Button-1>", callback)
canvas.bind('<Configure>', resize_event)
canvas.pack(expand=True, fill='both')
root.mainloop()

How to make background Transparent in TKinter by converting Label widget into Canvas widget?

I have a code that is working perfectly but it's not giving me transparent background, (here is the image ) after a research on web, I found the solution by using canvas widget, we can us images with transparent background.
Here is my code,
import tkinter as tk
from PIL import Image, ImageTk
def work(progress=1):
if progress > 300: # define the width by yourself
return
tmp_images = ImageTk.PhotoImage(progress_images.resize((progress, 10))) # the image size
lb.image = tmp_images # keep reference
lb["image"] = tmp_images # change the image
root.add = root.after(100, work, progress+10) # define the amplitude by yourself
root = tk.Tk()
progress_images = Image.open("path.png")
lb = tk.Label(root, bg="black")
lb.pack(side="left")
work()
root.mainloop()
but I am confused how to change Label widget into Canvas ? can anyone help me please ? I am noob in Tkinter still!!!
You can use canvas.create_text(...) to replace the labels and then use canvas.itemconfig(...) to update the labels. I got this from an other stack over flow question
reference link :-
add label ..
Below is a modified code using Canvas:
import tkinter as tk
from PIL import Image, ImageTk
def work(progress=10):
if progress > 300: # define the width by yourself
return
canvas.image = ImageTk.PhotoImage(progress_images.resize((progress, 30))) # the image size
canvas.itemconfig(pbar, image=canvas.image) # update image item
root.add = root.after(100, work, progress+10) # define the amplitude by yourself
root = tk.Tk()
progress_images = Image.open("path.png")
canvas = tk.Canvas(root, width=300, height=30, bg='black', highlightthickness=0)
canvas.pack()
pbar = canvas.create_image(0, 0, anchor='nw') # create an image item
work()
root.mainloop()

How to open a PIL image on every tkinter button press?

I am very new to Pyton and programming in general, and for my first project i am trying to make a script with Tkinter interface that should do the following:
Allow user to write some text into an entry,
on button click place that text on an image with a defined name,
save that image under the name that is current date and time,
repeat all of the above on button click.
The script works properly only once (after the first button click) then it places the entered text on previously entered text.
I gather that's because it opens the initial image only once and does other steps every time the button is clicked, but i can't seem to write the code that defines the initial image into command=lambda (it causes various errors).
Here is my code:
import tkinter as tk
from PIL import Image, ImageDraw, ImageFont
from datetime import datetime
def adresat1_function(self): draw.text(xy=(273, 215), text=(entry_1.get()),
fill=(0, 0, 0), font=font_type)
root = tk.Tk()
root.title("Postal")
root.maxsize(height=530, width=590,)
canvas = tk.Canvas(root, height=530, width=590, highlightthickness=0)
canvas.pack()
frame_1 = tk.Frame(canvas, bg='#75a3a3', bd=2)
frame_1.place(x=5, y=10, height=200, width=580, anchor='nw')
entry_1 = tk.Entry(frame_1, font=18,)
entry_1.place(x=202, y=0, width=374, height=22,)
#Image
image = Image.open('Blank.jpg')
font_type = ImageFont.truetype('arial.ttf',14,)
draw = ImageDraw.Draw(image)
#Button
button = tk.Button(frame_1, text = 'Fill', width=8,
command=lambda:
#Fill
(adresat1_function(entry_1.get()),
image.save(datetime.now().strftime("%Y-%m-%d %H-%M-%S") + '.jpg'),))
button.place(x=202, y=160, width=374, height=22,)
root.mainloop()
What has to be done to make this program save the entered text on a new image without rewriting it on top of the previously entered text?
I may not even know some of the Python core concepts, in that case sorry for dumb question. Thanks in advance.
Modifying your code like below, will solve the problem. What you want is that every time that you press the button, a new image copy is created and you can apply your text there:
import tkinter as tk
from PIL import Image, ImageDraw, ImageFont
from datetime import datetime
# Changes here.
def adresat1_function(self):
newImage = image.copy()
draw = ImageDraw.Draw(newImage)
draw.text(xy=(273, 215), text=(entry_1.get()),fill=(0, 0, 0), font=font_type)
newImage.save(datetime.now().strftime("%Y-%m-%d %H-%M-%S") + '.jpg')
root = tk.Tk()
root.title("Postal")
root.maxsize(height=530, width=590,)
canvas = tk.Canvas(root, height=530, width=590, highlightthickness=0)
canvas.pack()
frame_1 = tk.Frame(canvas, bg='#75a3a3', bd=2)
frame_1.place(x=5, y=10, height=200, width=580, anchor='nw')
entry_1 = tk.Entry(frame_1, font=18,)
entry_1.place(x=202, y=0, width=374, height=22,)
#Image
image = Image.open('Blank.jpg')
font_type = ImageFont.truetype('arial.ttf',14,)
newImage = None
#Button
button = tk.Button(frame_1, text = 'Fill', width=8,
command=lambda:
# Changes in fill.
(adresat1_function(entry_1.get()),))
button.place(x=202, y=160, width=374, height=22,)
root.mainloop()

tkinter window and background image don't align properly

I am writing a Simpsons trivia game as my first big programming project. My question is twofold:
Is this the right way to go about creating a background image? Keep in mind that my plan is to include the Simpsons theme song playing in the background as well as one or two buttons on top of the background image.
Assuming the code below is the right approach given what I want to accomplish, why am I getting a thin gray line on the left of my image and window? Ie. Why is the image not filling up the window perfectly like it is on the right side?
Here is my code:
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
root = Tk()
root.title("The Simpsons Trivia Game")
root.geometry('400x600')
root.resizable(0,0)
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
image = Image.open('E:\Simpsons Trivia Game\SimpsonsPic.png')
copy_of_image = image.copy()
photo = ImageTk.PhotoImage(image)
label = ttk.Label(root, image = photo)
label.bind('<Configure>', resize_image)
label.pack(fill=BOTH, expand = YES)
root.mainloop()
tkinter window with background image (left side of window not perfectly alligned with background image
I'm not sure I understand everything, but I managed to get rid of the border (at least on Linux) by doing:
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
root = Tk()
root.title("The Simpsons Trivia Game")
root.geometry("400x600")
root.resizable(0,0)
image = Image.open('/tmp/foobar.png')
photo = ImageTk.PhotoImage(image)
label = ttk.Label(root, image = photo)
label.pack()
label.place(relx=0.5, rely=0.5, anchor="center")
root.mainloop()

Categories