Tkinter displaying icon or JPG PNG image in windows by using Label or button using PILLOW library
Escape the path by using two backslashes if you have any char with can be used with backslash. Here \f can be understood as form feed, so we used two backslashes.
import tkinter as tk
my_w=tk.Tk()
my_w.geometry('300x100')
my_w.title('www.plus2net.com')
my_w.iconbitmap('D:\\images\\favicon.ico')
my_w.mainloop()
Dynamic Path with os Module
If you want your application to locate the icon file dynamically, use the os module to build the path relative to the script’s directory.
If PIL ( Python Image Library ) is not installed then use PIP to install it. You can check the status by using this command and check all installed libraries.
%pipfreeze
Here is the code to display .JPG image over a button.
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("840x570")
my_img = tk.PhotoImage(file = "H:\\top2.png")
print(my_img.width(),my_img.height()) # Width and height of the image
b1=tk.Button(my_w,image=my_img)
b1.grid(row=1,column=1)
my_w.mainloop()
import tkinter as tk
my_w=tk.Tk()
from PIL import Image,ImageTk
my_w.geometry('400x300')
my_w.title('www.plus2net.com')
my_img = ImageTk.PhotoImage(Image.open("H:/top2.jpg"))
print(my_img.width(),my_img.height()) # Print width and height of the image
b1=tk.Button(my_w,image=my_img)
b1.grid(row=1,column=1,padx=20,pady=20)
my_w.mainloop()
import tkinter as tk
my_w=tk.Tk()
from PIL import Image,ImageTk
my_w.geometry('400x300')
my_w.title('www.plus2net.com')
my_img = Image.open("H:/top2.jpg") # change the path of your image
print(my_img.size) # Print the tuple with width and height of the image
print('Width: ',my_img.size[0],' , Height: ',my_img.size[1])
my_img = ImageTk.PhotoImage(Image.open("H:/top2.jpg"))
b1=tk.Button(my_w,image=my_img)
b1.grid(row=1,column=1,padx=20,pady=20)
my_w.mainloop()
importtkinterastkfromPILimportImage, ImageTk# Create the imageimg = Image.new('RGB', (255,255), "black") # Create a new black imagepixels = img.load() # Create the pixel mapforiinimg.size[0]:
forjinimg.size[1]:
pixels[i,j] = (i, j, 100) # Set the colour accordinglymy_w = tk.Tk()
my_w.geometry('300x300')
my_w.title('www.plus2net.com')
my_img = ImageTk.PhotoImage(img)
b1 = tk.Button(my_w, image=my_img)
b1.grid(row=1, column=1, padx=20, pady=20)
my_w.mainloop()
Bitmap Image displaying
fromPILimportImageimporttkinterastkfromPILimportImage, ImageTk# Create a new bitmap image.img = Image.new("1", (200, 200))
# Get the image data.pixels = img.load()
# Set the pixel values.foriinimg.size[0]:
forjinimg.size[1]:
pixels[i, j] = 0if (i + j) % 5 == 0else255# Initialize Tkinter windowmy_w = tk.Tk()
my_w.geometry('300x300')
my_w.title('www.plus2net.com')
# Convert the image for Tkintermy_img = ImageTk.PhotoImage(img)
# Create a button with the imageb1 = tk.Button(my_w, image=my_img)
b1.grid(row=1, column=1, padx=20, pady=20)
# Run the Tkinter main loopmy_w.mainloop()