tkinter not displaying barcode image? - python

I'm using this python module called code128 that generates images of barcodes in code 128 barcode format.
The module works fine alone and produces the barcode desired. But now I'm trying to integrate it with tkinter and get tkinter to display it in a window but with no luck.
Tkinter just shows a black rectangle that would otherwise be the whole barcode. I'm not at all familiar with tkinter, but managed to borrow some functional code, but for some reason this barcode thing isn't working.
import tkinter as tk
from PIL import ImageTk, Image
import code128
#This creates the main window of an application
window = tk.Tk()
window.title("barcode test")
window.geometry("800x600")
#window.configure(background='grey')
#create a barcode image
barcode = code128.image('EL123456789US')
#barcode.show() #for testing purposes. the barcode is generated
#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img = ImageTk.PhotoImage(barcode)
#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
label = tk.Label(window, image = img)
label.image = img #keep a reference!
#The Pack geometry manager packs widgets in rows or columns.
label.pack(side = "bottom", fill = "both", expand = "yes")
#Start the GUI
window.mainloop()
I could just save the barcode to disk and load it from disk (it does work as I've already tried it) but I'm trying to avoid that as I need to display many barcodes one after another. Saving and reading from disk would be too costly.
Any help would be greatly appreciated. Thank you.

Related

How to slow down image display in Pillow

Probably an unusual question, but I am currently looking for a solution to display image files with PIL slower.
Ideally so that you can see how the image builds up, pixel by pixel from left to right.
Does anyone have an idea how to implement something like this?
It is a purely optical thing, so it is not essential.
Here an example:
from PIL import Image
im = Image.open("sample-image.png")
im.show()
Is there a way to "slow down" im.show()?
AFAIK, you cannot do this directly with PIL's Image.show() because it actually saves your image as a file to /var/tmp/XXX and then passes that file to your OS's standard image viewer to display on the screen and there is no further interaction with the viewer process after that. So, if you draw in another pixel, the viewer will not be aware and if you call Image.show() again, it will save a new copy of your image and invoke another viewer which will give you a second window rather than updating the first!
There are several possibilities to get around it:
use OpenCV's cv2.imshow() which does allow updates
use tkinter to display the changing image
create an animated GIF and start a new process to display that
I chose the first, using OpenCV, as the path of least resistance:
#!/usr/bin/env python3
import cv2
import numpy as np
from PIL import Image
# Open image
im = Image.open('paddington.png')
# Make BGR Numpy version for OpenCV
BGR = np.array(im)[:,:,::-1]
h, w = BGR.shape[:2]
# Make empty image to fill in slowly and display
d = np.zeros_like(BGR)
# Use "x" to avoid drawing and waiting for every single pixel
x=0
for y in range(h):
for x in range(w):
d[y,x] = BGR[y,x]
if x%400==0:
cv2.imshow("SlowLoader",d)
cv2.waitKey(1)
x += 1
# Wait for one final keypress to exit
cv2.waitKey(0)
Increase the 400 near the end to make it faster and update the screen after a greater number of pixels, or decrease it to make it update the screen after a smaller number of pixels meaning you will see them appear more slowly.
As I cannot share a movie on StackOverflow, I made an animated GIF to show how that looks:
I decided to try and do it with tkinter as well. I am no expert on tkinter but the following works just the same as the code above. If anyone knows tkinter better, please feel free to point out my inadequacies - I am happy to learn! Thank you.
#!/usr/bin/env python3
import numpy as np
from tkinter import *
from PIL import Image, ImageTk
# Create Tkinter Window and Label
root = Tk()
video = Label(root)
video.pack()
# Open image
im = Image.open('paddington.png')
# Make Numpy version for simpler pixel access
RGB = np.array(im)
h, w = RGB.shape[:2]
# Make empty image to fill in slowly and display
d = np.zeros_like(RGB)
# Use "x" to avoid drawing and waiting for every single pixel
x=0
for y in range(h):
for x in range(w):
d[y,x] = RGB[y,x]
if x%400==0:
# Convert the video for Tkinter
img = Image.fromarray(d)
imgtk = ImageTk.PhotoImage(image=img)
# Set the image on the label
video.config(image=imgtk)
# Update the window
root.update()
x += 1

Display Image from Mysql directly to kivy window

I have checked out this answer but it does not seem to explain clearly what is happening in order to display images directly from mysql db to a kivy window directly, assuming we already have the blob data from mysql in a variable called loaded_Image.
How can we display loaded_Image into window? {Preferably using a dynamic Image Widget and not from .kv file}
Please help if you have accomplished this before.
I figured this out to the best of my understanding
First load an image in form of blob data using normal mysql python and store in a variable, my case called image, you convert it as below to data then add data to CoreImage
image = value[9]
data = io.BytesIO(image)
img = CoreImage(data, ext="png").texture
Make sure you use this for your import
from kivy.uix.image import Image, CoreImage
Next ensure you add a default image within your project folder and call it using widget as follows
widget = Image(source = 'a.jpg')
Set the texture of widget to img, then add it to your target widget or parent
widget.texture = img
target.add_widget(widget)
The full working code like below:
image = value[9] #Add your data
data = io.BytesIO(image)
img = CoreImage(data, ext="png").texture
widget = Image(source = 'a.jpg')
widget.texture = img
target.add_widget(widget)

Tkinter image blank (without PIL)

I am making an animated presentation and I want to add an image to it, but I can't use PIL because it will be presented at school, where PIL isn't installed, so I used the method given by the website http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm, but it doesn't work - my slide is still blank. What should I do?
Here is my code (copied almost completely from the website - did I miss something out?):
photo = PhotoImage('Alveoli.png')
label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
You can not open .png files without using an external image library. Since PIL isn't available I'd think other similar libraries aren't either.
EDIT: Note: PNG files are supported for tkinter v8.6+.
The only possibility that comes to mind is converting the image to another, compatible format like GIF or PGM
If you have the image in one of those formats you can simply add them. It worked just fine for me with this code:
from tkinter import *
root = Tk()
photo = PhotoImage(file="img.ppm")
img = Label(root, image=photo)
img.image = photo
img.place(x=0, y=0)
root.mainloop()

Tkinter : How to change position of text on image

I have developed some application on my laptop with python and tkinter. Then, I was stuck at some point. Question is : how can I change text position on image.
import tkinter as tk
from PIL import Image, ImageTk
path_to_pic = "....."
root = tk.Tk()
pic = Image.open(path_to_pic)
tkpic = ImageTk.PhotoImage(pic)
tk.Label(root, image = tkpic, text = ".....", compound = tk.CENTER).pack()
root.mainloop()
This shows that my text appears on the picture, only on the center. I would like to move my text little by little and find best position. Do you know any solution or similar way to achieve this ?
You can move text horizontally and vertically by adding spaces and '\n's respectively, to any side(s) of the text you wish:
text = "caption \n\n\n\n\n\n\n"
This will put "caption" at the top left of the text.

View a document TKinter

I am new to TKinter and cant seem to find any examples on how to view a document in a window. What I am trying to accomplish is that when selecting a PDF or TIF it will open the file and show the first page in a window using TKinter. Is this possible?
A long time has passed since this question was posted but, for those still looking for a solution, here's one I've found :
https://github.com/rk700/PyMuPDF/wiki/Demo:-GUI-script-to-display-a-PDF-using-wxPython-or-Tkinter
Basically, it uses PyMuPDF, a python binding for MuPDF. MuPDF is a lightweight document viewer capable of displaying a few file formats, such as pdf and epub.
I quote the code used for TKinter:
This demo can easily be adopted to Tkinter. You need the imports
from Tkinter import Tk, Canvas, Frame, BOTH, NW
from PIL import Image, ImageTk
and do the following to display each PDF page image:
#-----------------------------------------------------------------
# MuPDF code
#-----------------------------------------------------------------
pix = doc.getPagePixmap(pno - 1) # create pixmap for a page
#-----------------------------------------------------------------
# Tkinter code
#-----------------------------------------------------------------
self.img = Image.frombytes("RGBA",
[pix.width, pix.height],
str(pix.samples))
self.photo = ImageTk.PhotoImage(self.img)
canvas = Canvas(self, width=self.img.size[0]+20,
height=self.img.size[1]+20)
canvas.create_image(10, 10, anchor=NW, image=self.photo)
canvas.pack(fill=BOTH, expand=1)
No, it is not possible to show a TIF or PDF in a Tkinter window. Your main options are to show plain text, and to show images (.gif with plain Tkinter, other formats if you include PIL - the python imaging library).
Nothing is impossible my friend!
Try using snippets from this:
http://nedbatchelder.com/blog/200712/extracting_jpgs_from_pdfs.html
to convert the pdf to an image.
I would then display the image on a label using PIL and Tkinter.
And I think Tif files should display on a label without problems IIRC.
The following code uses the old library pypdfocr (I had to modify it to work with Python 3) and Ghostscript (Ghostscript needs to be installed outside of Python and so isn't ideal for software to be distributed) to convert each of the PDF's pages into an image that can then be opened by PIL. In the sense that it uses very old libraries and packages, DrD's answer is probably more appropriate.
import glob
import PIL.Image
import PIL.ImageTk
import pypdfocr.pypdfocr_gs as pdfImg
files = glob.glob(pdfImg.PyGs({}).make_img_from_pdf(file_name)[1])
pages = [PIL.ImageTk.PhotoImage(PIL.Image.open(file)) for file in files]

Categories