Background image not appearing in tkinter - python

I'm trying to put a background image in my tkinter project, but despite of several attempts it's simply not showing up.
Here is the code:
import tkinter
from PIL import ImageTk,Image
show_screen = tkinter.Tk()
show_screen.geometry('900x900')
show_screen.title("LEARNTECH OPE")
img_show = Image.open("C:\PYTHON IDE\RemoteProctoring_Featured.png")
show_image = ImageTk.PhotoImage(img_show)
show_label = tkinter.Label(show_screen,font=("Arial Bold",10),fg="blue",
text="FILL THE NECESSARY DETAILS GIVEN BELOW")
show_label.place(x=600,y=0)
enter_field = tkinter.Entry(show_screen,width=50)
enter_field.place(x=600,y=200)
def clicked():
ref = "Welcome" + enter_field.get()
show_label.configure(text=ref)
show_button = tkinter.Button(show_screen,text="CLICK TO EXIT",
fg="green",command=clicked).place(x=600,y=400)
show_screen.mainloop()

As I said in a comment, images can only be displayed as part of some tkinter widget. Below is an example of doing that by putting the image in a Label. I also added code to resize the image to fill the window (aka "screen" in your code).
import tkinter
from PIL import ImageTk, Image
WIDTH, HEIGHT = 900, 900
IMG_PATH = r"C:\PYTHON IDE\RemoteProctoring_Featured.png" # Note 'r' prefix.
show_screen = tkinter.Tk()
show_screen.geometry('{}x{}'.format(WIDTH, HEIGHT))
show_screen.title("LEARNTECH OPE")
# Place background image on a Label widget.
tmp_img = Image.open(IMG_PATH).resize((WIDTH, HEIGHT), Image.ANTIALIAS)
bkg_img = ImageTk.PhotoImage(tmp_img)
bkg_label = tkinter.Label(show_screen, image=bkg_img)
bkg_label.img = bkg_img # Keep a reference in case this code put is in a function.
bkg_label.place(relx=0.5, rely=0.5, anchor='center') # Place in center of window.
enter_field = tkinter.Entry(show_screen,width=50)
enter_field.place(x=600,y=200)
show_label = tkinter.Label(show_screen,font=("Arial Bold",10),fg="blue",
text="FILL THE NECESSARY DETAILS GIVEN BELOW")
show_label.place(x=600,y=0)
def clicked():
ref = "Welcome " + enter_field.get()
show_label.configure(text=ref)
show_button = tkinter.Button(show_screen,text="CLICK TO EXIT",
fg="green",command=clicked)
show_button.place(x=600,y=400)
show_screen.mainloop()

Related

tkinter get background image to fill entire window

I've been trying to have an image as background for my project. I found some code that places it in a label and this works fine except the sizing of it doesn't seem to work and empty spaces show up on the sides (see picture)
My code is:
from tkinter import *
from PIL import ImageTk, Image
#make a window
ws = Tk()
ws.title("window")
#get wigth & height of screen
width= ws.winfo_screenwidth()
height= ws.winfo_screenheight()
#set screensize as fullscreen and not resizable
ws.geometry("%dx%d" % (width, height))
ws.resizable(False, False)
# put image in a label and place label as background
imgTemp = Image.open("images/wallpaper.png")
img2 = imgTemp.resize((height,1800))
img = ImageTk.PhotoImage(img2)
label = Label(ws,image=img)
label.pack(side='top',fill=Y,expand=True)
#text = Text(ws,height=10,width=53)
#text.place(x=30, y=50)
#button = Button(ws,text='SEND',relief=RAISED,font=('Arial Bold', 18))
#button.place(x=190, y=250)
ws.mainloop()

Is it possible to provide animation on image ? - Tkinter

I'm developing a GUI in Tkinter and want to apply animation in the below GIF on the image when it appears.
Here is my code,
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
frame = Frame(root)
frame.pack()
canvas = Canvas(frame, width=300, height=300, bd=0, highlightthickness=0, relief='ridge')
canvas.pack()
background = PhotoImage(file="background.png")
canvas.create_image(300,300,image=background)
my_pic = PhotoImage(file="start000-befored.png")
frame.after(1000, lambda: (canvas.create_image(50,50,image=my_pic, anchor=NW))) #and on this image, I want to give the effect.
root.mainloop()
Instead of clicking on the play button as shown in GIF, the image should automatically appears after 1 second like this animation and stays on screen. (No closing option).
I'm not 100% sure I understood the problem, but I'll describe how to animate an image.
Tkinter does not contain functions for animating images so you'll have to write them yourself. You will have to extract all subimages, subimage duration and then build a sequencer to swap subimages on your display.
Pillow can extract image sequences. WEBP images seems to only support one frame duration whereas GIF images may have different frame duration for each subimage. I will use only the first duration for GIF images even if there is many. Pillow does not support getting frame duration from WEBP images as far as I have seen but you gan read it from the file, see WebP Container Specification.
Example implementation:
import tkinter as tk
from PIL import Image, ImageTk, ImageSequence
import itertools
root = tk.Tk()
display = tk.Label(root)
display.pack(padx=10, pady=10)
filename = 'images/animated-nyan-cat.webp'
pil_image = Image.open(filename)
no_of_frames = pil_image.n_frames
# Get frame duration, assuming all frame durations are the same
duration = pil_image.info.get('duration', None) # None for WEBP
if duration is None:
with open(filename, 'rb') as binfile:
data = binfile.read()
pos = data.find(b'ANMF') # Extract duration for WEBP sequences
duration = int.from_bytes(data[pos+12:pos+15], byteorder='big')
# Create an infinite cycle of PIL ImageTk images for display on label
frame_list = []
for frame in ImageSequence.Iterator(pil_image):
cp = frame.copy()
frame_list.append(cp)
tkframe_list = [ImageTk.PhotoImage(image=fr) for fr in frame_list]
tkframe_sequence = itertools.cycle(tkframe_list)
tkframe_iterator = iter(tkframe_list)
def show_animation():
global after_id
after_id = root.after(duration, show_animation)
img = next(tkframe_sequence)
display.config(image=img)
def stop_animation(*event):
root.after_cancel(after_id)
def run_animation_once():
global after_id
after_id = root.after(duration, run_animation_once)
try:
img = next(tkframe_iterator)
except StopIteration:
stop_animation()
else:
display.config(image=img)
root.bind('<space>', stop_animation)
# Now you can run show_animation() or run_animation_once() at your pleasure
root.after(1000, run_animation_once)
root.mainloop()
There are libraries, like imgpy, which supports GIF animation but I have no experience in usig any such library.
Addition
The duration variable sets the animation rate. To slow the rate down just increase the duration.
The simplest way to put the animation on a canvas it simply to put the label on a canvas, see example below:
# Replace this code
root = tk.Tk()
display = tk.Label(root)
display.pack(padx=10, pady=10)
# with this code
root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=500)
canvas.pack(padx=10, pady=10)
display = tk.Label(canvas)
window = canvas.create_window(250, 250, anchor='center', window=display)
Then you don't have to change anything else in the program.

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

Images not getting applied on the button in Tkinter

The following project is supposed to show a message when clicking a certain colored button. But, whenever I execute the program it shows blank(white) buttons in the correct alignment, etc. Due to some reason the images are not loaded.
In future, I plan to add different images hence testing with colored image created in Paint and not in-built commands to show the color.
I will add the result below after the code.
Edit: All images are 100x100 pixels created in Microsoft Paint.I have tried other modules like PIL but to no avail.
# importing the module
import tkinter
import tkinter.messagebox
from tkinter import *
# importing the module
# initialising tkinter
class window(Frame):
def __init__(self,master = None):
Frame.__init__(self,master)
self.master = master
# initialising tkinter
# creating the window
root = Tk()
app = window(root)
root.geometry("350x350")
# creating the window
# colours
WHITE = (255,255,255)
BLACK = (0,0,0)
BLUE = (0,0,255)
RED = (255,0,0)
# colours
# image
red_image = "red.png"
blue_image = "blue.png"
yellow_image = "yellow.png"
green_image = "green.png"
# image
# creating a button function
def create_button(x,y,color,color2,picture):
click = Button(root, image = PhotoImage(picture), width= 150, height=150, command = lambda : tkinter.messagebox.showinfo( "Hello Python", "This is " + color))
click.image = PhotoImage(picture)
click.grid( row = x, column = y)
# creating a button function
create_button(0,0,'red','pink',red_image)
create_button(0,2,'blue','lightblue',blue_image)
create_button(2,0,'green','lightgreen',green_image)
create_button(2,2,'yellow','lightyellow',yellow_image)
# starting the widget
root.mainloop()
# starting the widget
There are two issues in your code:
You passed filename to PhotoImage() without using file keyword: PhotoImage(picture) should be PhotoImage(file=picture)
You did not keep the reference of the image assigned to button, but another instance of image
Below is the updated create_button() function that fixes the issues:
def create_button(x, y, color, color2, picture):
image = PhotoImage(file=picture)
click = Button(root, image=image, width=150, height=150, command=lambda: tkinter.messagebox.showinfo("Hello Python", "This is "+color))
click.image = image
click.grid(row=x, column=y)
For adding image in Button you have not use appropriate keywords.
Here is a simple example for you to add image in button
from tkinter import *
from tkinter.ttk import *
# creating tkinter window
root = Tk()
# Adding widgets to the root window
Label(root, text = 'Image adding', font =( 'Verdana',15)).pack(side = TOP, pady = 10)
# Creating a photoimage object to use image
photo = PhotoImage(file = "C:\Gfg\circle.png")
# here, image option is used to
# set image on button
Button(root, text = 'Click Me !', image = photo).pack(side = TOP)
root.mainloop()
I think it may help you

Display IMAGE and TEXTBOX simultanously in a "form" with PYTHON

Here what I'd like
I'm new in PYTHON. I'm trying to display IMAGE and TEXTBOX simultaneously in a "Form" with PYTHON.
My problem: Image is not visible on the screen. How to solve that problem?
Thanks,
My code:
import tkinter as tk
from PIL import ImageTk, Image
#This creates the main window of an application
window = tk.Tk()
window.title("SEE image and ENTER its information")
window.geometry("600x400")
window.configure(background='grey')
# Create textbox in window
text_widget = tk.Text(window)
text_widget.insert('insert',"Enter image information here")
text_widget.pack(anchor = "w", padx = 50, pady = 50)
#Creates a tkinter-compatible photo image.
path = "Picture.jpg"
img = ImageTk.PhotoImage(Image.open(path))
#The Label widget is a standard tkinter widget used to display a text or
image on the screen.
panel = tk.Label(window, image = img)
#The Pack geometry manager packs widgets in rows or columns.
#panel.pack(side = "bottom", fill = "both", expand = "no")
panel.pack()
#Start the GUI
window.mainloop()
import tkinter as tk
from PIL import ImageTk, Image
#This creates the main window of an application
window = tk.Tk()
window.title("SEE image and ENTER its information")
window.geometry("600x400")
window.configure(background='grey')
#Creates a tkinter-compatible photo image.
path = "Picture.jpg"
img = ImageTk.PhotoImage(Image.open(path))
#The Label widget is a standard tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)
# Create textbox in window
text_widget = tk.Text(panel)
text_widget.insert('insert',"Enter image information here")
text_widget.pack(anchor = "w", padx = 50, pady = 50)
#The Pack geometry manager packs widgets in rows or columns.
#panel.pack(side = "bottom", fill = "both", expand = "no")
panel.pack()
#Start the GUI
window.mainloop()
If that's the idea, do you wish to display information to the user or for user to enter information?
Assuming the latter, here is something.
import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk()
window.title("SEE image and ENTER its information")
window.geometry("600x400") # You can drop this line if you want.
window.configure(background='grey')
path = "Picture.jpg"
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(window, image = img)
txtVar = tk.StringVar(None)
usrIn = tk.Entry(window, textvariable = txtVar, width = 90)
usrIn.grid(row = 50, column = 60)
usrIn.pack()
panel.pack()
window.mainloop()
ThetxtVar can be used for accepting info from user. You may also have to use the Button feature if needed.
Here is nice link.

Categories