how Write a text on png image Using python PIL - python

I am trying to code for make a registration System and Identity Card printer first form done with making data import to database using sqlite3 database and tkinter GUI.this form for get data from database and write that data text on png image.that png image after written data it is the identity card.
**so this is the problem..code run without any errors.but image not written data.for try this code firstly i didn't use database data.i used data from string variable **
import sqlite3
from tkinter import Tk, Button, Canvas
from PIL import Image, ImageFont, ImageDraw
connection = sqlite3.connect("school.db")
tao = Tk()
tao.title("Mayurapada Central Collage")
tao.configure(bg = '#6699ff')
canvas = Canvas(tao,width = 600,height = 400,bg = '#6699ff')
def imgs():
img = Image.open("C:\\Users\\TAO\\Desktop\\New\\02.png")
#img.show()
str01 = "Hello World"
font = ImageFont.truetype("arial.ttf",200)
w,h = font.getsize(str01)
print(str01)
draw = ImageDraw.Draw(img)
draw.text(((900-w)/2,(900-h)/2),str01,font = font,fill = "black")
img.show()
button01 = Button(tao,text = "Preview",bd = 7,padx = 5,pady = 5,command =
imgs).place(x = 50,y = 300)
canvas.pack()
tao.mainloop()

Related

How to set the speed of a gif in Python

i am using Python and I inserted a gif in my project. The issue is when i start the application the gif in the application runs in different way than orginal gif. I think that the frames in the gif are run in different speed. How to set the original gif?
I imported PIL and tkinter. This is the code:
import threading
from tkinter import *
from PIL import Image, ImageTk, ImageSequence
def play_gif():
global img
img = Image.open("Gifs/beaming_face_with_smiling_eyes.gif")
lbl = Label(root)
lbl.place(x = 0, y = 0)
for img in ImageSequence.Iterator(img):
img = ImageTk.PhotoImage(img)
lbl.config(image = img)
root.update()
def exit():
root.destroy()
threading.Timer(3.0, play_gif).start()
Button(root,text = "exit", command=exit).place(x = 450, y = 300)
root.mainloop()

How to display the video in tkinter canvas frame by frame?

I am dealing with tkinter and opencv to display frames of video in tkinter canvas. my code is as following :
import tkinter as tk
from PIL import ImageTk as itk
from PIL import Image
from tkinter import filedialog as fd
import cv2
window = tk.Tk()
class window_tk():
def __init__(self,main):
self.canvas = tk.Canvas(main, bg='white' )
self.img = itk.PhotoImage(file=self.init_img_route)
self.bg= self.canvas.create_image(0,0,anchor = tk.NW,image=self.img)
self.vid = None
def load_video(self):
self.foldername = fd.askopenfilename(parent=window,initialdir="C:/",title='Select a video file to load.',filetypes=[('video files','*.wmv *.mp4 *.mov *.avi')])
self.label_foldername.config(text='Video Load : '+self.foldername)
self.current_pic_num=0
try:
self.vid = cv2.VideoCapture(self.foldername)
frame_number =0
print(self.vid,self.vid.isOpened())
self.frame_count = 0
if self.vid.isOpened():
vid_w = self.vid.get(cv2.CAP_PROP_FRAME_WIDTH)
vid_h = self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT)
vid_f = self.vid.get(cv2.CAP_PROP_FPS)
ret,frame = self.vid.read()
#cv2.imshow('frame',frame)
frame_convert = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
#print(self.frame_count, vid_w,vid_h,vid_f,frame.shape)
imgg = itk.PhotoImage(Image.fromarray(frame_convert))
self.canvas.itemconfig(self.bg, image = imgg)
self.canvas.pack(fill='both',expand=1)
# frame_number+=1
except IndexError:
pass
I confirmed that frame has successfully loaded by checking it as cv2.imshow(), but The canvas only shows the white empty image. Is there anything I missed ?
I found answer and leave the solution for my study.
I changed imgg to self.img and let it globally used in class.
I don't know why it solved the problem so if anyone can explain the reason thank you very much.

How do i properly attach a .PNG file into a TKINTER button?

I am doing a battleship game and a function below that executes to create a new button with an explosion image as it's background. I am using Mac & python 3.7
global redraw_gameboard
global Player
global AI_player
script_dir = os.path.dirname(__file__)
rel_path = "explode.png"
image = ImageTk.PhotoImage(file=os.path.join(script_dir, rel_path))
new_button = Button(redraw_gameboard,
height = 2,
width = 4,
command= already_shot,
image=image)
new_button.grid(row = row, column = column)
This is what is coming out:
I am not sure what you expect, since I don't know what does the "explode.png" image look like. Also, when asking questions on stackoverflow, please always try to post a minimal reproducible example.
However, as I understand, the problem probably comes from the fact that the image is bigger than the button, and it is cropped. Then, only the upper left part of the image is displayed in your buttons.
Suggested solution:
(You will need to install the pillow package if it is not done yet)
import os
from PIL import Image, ImageTk
import tkinter
# Sizes in pixels
BUTTON_HEIGHT = 40
BUTTON_WIDTH = 40
root = tkinter.Tk()
script_dir = os.path.dirname(__file__)
rel_path = "explode.png"
image = Image.open(os.path.join(script_dir, rel_path))
image = image.resize((BUTTON_WIDTH,BUTTON_HEIGHT))
imtk = ImageTk.PhotoImage(image)
# Using a void image for other buttons so that the size is given in pixels too
void_imtk = tkinter.PhotoImage(width=BUTTON_WIDTH, height=BUTTON_HEIGHT)
def create_button(row, column, im):
new_button = tkinter.Button(root,
height = BUTTON_HEIGHT,
width = BUTTON_WIDTH,
image=im)
new_button.grid(row = row, column = column)
create_button(0,0, imtk)
create_button(0,1, void_imtk)
create_button(1,0, void_imtk)
create_button(1,1, imtk)
root.mainloop()
Of course, you will want to make some changes for your program, e.g. using your widget architecture.

Issue with showing and updating image in Tkinter

I'm able to display an image if I grab it from one location, but I need the image to update along with the related article from a website. So if you open my application tomorrow, a different image will appear. So needless to say, I'm using regular expressions but the image just won't show on the label. Here's my code so far:
from Tkinter import *
import Tkinter as tk
import re
from re import findall
from urllib import urlopen
import datetime
from PIL import Image
from PIL import Image, ImageTk
from cStringIO import StringIO
root = Tk()
root.title("Science and Technology")
root.geometry("600x600")
main_label = Label(root, text = "Science and Technology")
main_label.pack()
all_image_height = 400
all_image_width = 400
dash = "-"
now = datetime.datetime.now()
text_area = LabelFrame(root, borderwidth = 2)
text_area.pack(padx = 10, pady = 10, expand = 1, fill= BOTH)
date = Label(text_area)
date.pack()
content_t = Label(text_area)
content_t.pack()
imag = Label(text_area)
imag.pack()
def science_all():
sw_img = 300
sh_img = 300
webScience = urlopen(urlScience)
html_code = webScience.read()
webScience.close()
titl = findall("'name'>(.+[a-zA-Z])</title>", html_code)[0]
date1 = str(now.day),(dash),(now.month),(dash),(now.year)
content_title = findall('itemprop="name">(.+[a-zA-Z])</h5>',html_code)[0]
text_area.config(text = titl)
date.config(text = date1)
content_t.config(text = content_title)
url2 = "http://www.wired.com/"
im = urlopen(url2)
html_code2 = im.read()
im.close()
global image_file
global photo_image
global imag
imag2 = findall('<img src="(.*)">', html_code2)
image_file = Image.open(StringIO(html_code2))
photo_image = ImageTk.PhotoImage(image_file)
imag.config(image=imag2)
Science = Button(root, text="Science",
command = science_all)
Science.pack(side=LEFT)
urlScience = 'http://www.wired.com/'
root.mainloop()
It works fine when using a link for one specific image from a website but when regular expressions come into it, that's where it all gets difficult for me. Any suggestions would be very helpful. Thanks.

Resizing pictures in PIL in Tkinter

I'm currently using PIL to display images in Tkinter. I'd like to temporarily resize these images so that they can be viewed more easily. How can I go about this?
Snippet:
self.pw.pic = ImageTk.PhotoImage(Image.open(self.pic_file))
self.pw.pic_label = TK.Label(self.pw , image=self.pw.pic,borderwidth=0)
self.pw.pic_label.grid(column=0,row=0)
Here's what I do and it works pretty well...
image = Image.open(Image_Location)
image = image.resize((250, 250), Image.ANTIALIAS) ## The (250, 250) is (height, width)
self.pw.pic = ImageTk.PhotoImage(image)
There you go :)
EDIT:
Here is my import statement:
from Tkinter import *
import tkFont
from PIL import Image
And here is the complete working code I adapted this example from:
im_temp = Image.open(Image_Location)
im_temp = im_temp.resize((250, 250), Image.ANTIALIAS)
im_temp.save("ArtWrk.ppm", "ppm") ## The only reason I included this was to convert
## The image into a format that Tkinter woulden't complain about
self.photo = PhotoImage(file="ArtWrk.ppm") ## Open the image as a tkinter.PhotoImage class()
self.Artwork.destroy() ## Erase the last drawn picture (in the program the picture I used was changing)
self.Artwork = Label(self.frame, image=self.photo) ## Sets the image too the label
self.Artwork.photo = self.photo ## Make the image actually display (If I don't include this it won't display an image)
self.Artwork.pack() ## Repack the image
And here are the PhotoImage class docs: http://www.pythonware.com/library/tkinter/introduction/photoimage.htm
Note...
After checking the pythonware documentation on ImageTK's PhotoImage class (Which is very sparse) I appears that if your snippet works than this should as well as long as you import the PIL "Image" Library an the PIL "ImageTK" Library and that both PIL and tkinter are up-to-date. On another side-note I can't even find the "ImageTK" module life for the life of me. Could you post your imports?
if you don't want save it you can try it:
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
same = True
#n can't be zero, recommend 0.25-4
n=2
path = "../img/Stalin.jpeg"
image = Image.open(path)
[imageSizeWidth, imageSizeHeight] = image.size
newImageSizeWidth = int(imageSizeWidth*n)
if same:
newImageSizeHeight = int(imageSizeHeight*n)
else:
newImageSizeHeight = int(imageSizeHeight/n)
image = image.resize((newImageSizeWidth, newImageSizeHeight), Image.ANTIALIAS)
img = ImageTk.PhotoImage(image)
Canvas1 = Canvas(root)
Canvas1.create_image(newImageSizeWidth/2,newImageSizeHeight/2,image = img)
Canvas1.config(bg="blue",width = newImageSizeWidth, height = newImageSizeHeight)
Canvas1.pack(side=LEFT,expand=True,fill=BOTH)
root.mainloop()
the easiest might be to create a new image based on the original, then swap out the original with the larger copy. For that, a tk image has a copy method which lets you zoom or subsample the original image when making the copy. Unfortunately it only lets you zoom/subsample in factors of 2.

Categories

Resources