How to use an image for the background in tkinter? - python

#import statements
from Tkinter import *
import tkMessageBox
import tkFont
from PIL import ImageTk,Image
Code to import image:
app = Tk()
app.title("Welcome")
image2 =Image.open('C:\\Users\\adminp\\Desktop\\titlepage\\front.gif')
image1 = ImageTk.PhotoImage(image2)
w = image1.width()
h = image1.height()
app.geometry('%dx%d+0+0' % (w,h))
#app.configure(background='C:\\Usfront.png')
#app.configure(background = image1)
labelText = StringVar()
labelText.set("Welcome !!!!")
#labelText.fontsize('10')
label1 = Label(app, image=image1, textvariable=labelText,
font=("Times New Roman", 24),
justify=CENTER, height=4, fg="blue")
label1.pack()
app.mainloop()
This code doesn't work. I want to import a background image.

One simple method is to use place to use an image as a background image. This is the type of thing that place is really good at doing.
For example:
background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
You can then grid or pack other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.
Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:
background_label.image = background_image

A simple tkinter code for Python 3 for setting background image .
from tkinter import *
from tkinter import messagebox
top = Tk()
C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()
top.mainloop

You can use this:
root.configure(background='your colour')
Example:-
import tkinter
root=tkiner.Tk()
root.configure(background='pink')

Related

Tkinker and online resizing of .jpg with Pillow (PIL)

Trying to include a slider to resize images online in a Tkinker-GUI-Application of python.
Problem: Canvas Resizing works, Inital Show of original sized image, too. But when using the slider the picture is not resized - it just shows very short in the adjusted size and is then somehow "overwritten" by the original one.
from tkinter import *
from turtle import width
from PIL import Image, ImageTk
import FileDownloader
window = Tk()
window.title ('Price Catcher')
#PIL to open a jpg and store a Tk compatible objekct
headerpic = Image.open("./10374_0.jpg")
def resizePictures(scalerValue):
print(scalerValue)
print(window.canvas.find_all())
headerpicTk = ImageTk.PhotoImage(headerpic.resize((int(scalerValue), int(scalerValue)), Image.ANTIALIAS))
window.canvas.config(width=int(scalerValue), height=int(scalerValue))
#window.canvas.delete("all")
canvas_id = window.canvas.create_image(0,0, anchor=NW, image=headerpicTk)
window.canvas.update()
#Picture Resizer
PicResizeScale = IntVar() #Control Variable to use for Picture Resizing Value of Scaler
window.scale = Scale(window, label='Bildgröße in %', orient=HORIZONTAL, resolution=10, length=300, from_=0, to=200, command=resizePictures)
window.scale.set(100)
window.scale.pack(side=TOP)
#PIL to open a jpg and store a Tk compatible objekct
headerpic = Image.open("./10374_0.jpg")
headerpicTk = ImageTk.PhotoImage(headerpic)
#Place the opject to the canvas
window.canvas = Canvas(window, width=100, height=100)
window.canvas.pack()
canvas_id = window.canvas.create_image(0,0, anchor=NW, image=headerpicTk)
window.downloadbutton = Button(window, text='Download Bild', command=FileDownloader.FileDownloader("https://www.silbertresor.de/images/product_images/info_images/10374_0.jpg", ".\\10374_0.jpg"), justify= LEFT)
window.downloadbutton.pack(side = BOTTOM)
window.exitbutton = Button(window, text='Schließen', command=exit, justify= RIGHT)
window.exitbutton.pack(side= BOTTOM)
window.mainloop()
Any hints - i'm lost :(..
PhotoImage has bug which removes image when it is assigned to local variable in function.
And inside resizePictures you assign new PhotoImage to local variable headerpicTk.
You have to add global headerpicTk to assign PhotoImage to global variable headerpicTk.
def resizePictures(scalerValue):
global headerpicTk
print(scalerValue)
# ...rest ...
That's all.

Why is my background image not resizing itself? How can I solve this?

I'm trying to make the background image rescale with the window size, but it's not working. How come? how can I solve this?
from tkinter import *
from PIL import Image, ImageTk
window = Tk()
window.geometry("1300x700")
window.title('Monopoly')
background_image = PhotoImage(file="board.png")
background_label = Label(window, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
background_label.pack()
def resizer(event):
global bg1, resized_bg, new_bg
bg1 = Image.open('board.png')
resized_bg = bg1.resize((event.width, event.height))
new_bg = PhotoImage(resized_bg)
background_label.config(image=new_bg)
label = Label(window, text='this is a test').pack()
window.bind('<Configure>', resizer)
window.mainloop()
Your new_bg variable is going out of scope so you need to keep it alive by doing background_label.img = new_bg. Also to convert a PIL image to a tkinter image you need to use ImageTk.PhotoImage. So change your code to:
from tkinter import *
from PIL import Image, ImageTk
window = Tk()
window.geometry("1300x700")
window.title('Monopoly')
background_image = PhotoImage(file="board.png")
background_label = Label(window, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
background_label.pack()
def resizer(event):
global bg1, resized_bg, new_bg
bg1 = Image.open('board.png')
resized_bg = bg1.resize((event.width, event.height))
new_bg = ImageTk.PhotoImage(resized_bg) # Changed this
background_label.img = new_bg # Changed this
background_label.config(image=new_bg)
label = Label(window, text='this is a test').pack()
window.bind('<Configure>', resizer)
window.mainloop()
Also you shouldn't really use both .pack and .place on the same widget. You first did this: background_label.place(...) then this: background_label.pack()

Tkinter: Adding Image with transparent background to Button

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

Grid and Pack same time :( what can i do to use pack or grid together or is there another way [duplicate]

#import statements
from Tkinter import *
import tkMessageBox
import tkFont
from PIL import ImageTk,Image
Code to import image:
app = Tk()
app.title("Welcome")
image2 =Image.open('C:\\Users\\adminp\\Desktop\\titlepage\\front.gif')
image1 = ImageTk.PhotoImage(image2)
w = image1.width()
h = image1.height()
app.geometry('%dx%d+0+0' % (w,h))
#app.configure(background='C:\\Usfront.png')
#app.configure(background = image1)
labelText = StringVar()
labelText.set("Welcome !!!!")
#labelText.fontsize('10')
label1 = Label(app, image=image1, textvariable=labelText,
font=("Times New Roman", 24),
justify=CENTER, height=4, fg="blue")
label1.pack()
app.mainloop()
This code doesn't work. I want to import a background image.
One simple method is to use place to use an image as a background image. This is the type of thing that place is really good at doing.
For example:
background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
You can then grid or pack other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.
Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:
background_label.image = background_image
A simple tkinter code for Python 3 for setting background image .
from tkinter import *
from tkinter import messagebox
top = Tk()
C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()
top.mainloop
You can use this:
root.configure(background='your colour')
Example:-
import tkinter
root=tkiner.Tk()
root.configure(background='pink')

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

Categories