Tkinter:Cant place image which imported from Pixmap inside text widget using button

328 Views Asked by At

So i am using python 3 and got confused why the image doesnt show up in text widget after excuted the following code:

from tkinter import *
import fitz

root=Tk()
filenew=fitz.open(r'C:\Users\azoka\Desktop\Python\b.pdf')

text_1=Text(root,width=100,height=100,bg='gray').pack(side=LEFT,expand=FALSE)

def Show(): 
   pix =filenew.getPagePixmap(0)   # 0 is page number
   pix1=fitz.Pixmap(pix,0)
   img =pix1.getImageData("ppm")
   timg=PhotoImage(data=img)
   frame=[]
   frame.append(timg)
   text_1.image_create(END,image=timg)

Shower=Button(win1,text='show',bg='navy',fg='light cyan',width=5,height=1,command=Show)
Shower.place(x=1000,y=360)

root.mainloop()

The image just dont show up after clicked the button but it doesnt show any code error,I am new to python and cant figure out. I want my img be shown without altering the Show()function.

-Appreciate for helpful answers!-

1

There are 1 best solutions below

1
On

I tried to use the from previous code but not works I made some fix with last version today, see fix bellow with simplifications

from tkinter import *
from PIL import Image, ImageTk

import fitz


root = Tk()
file = "yourfile.pdf"
doc = fitz.open(file)
page = doc.load_page(0)  # loads page number 'pno' of the document (0-based)
pix = page.get_pixmap()
mode = "RGBA" if pix.alpha else "RGB"
img = Image.frombytes(mode, [pix.width, pix.height], pix.samples)
frame_image = ImageTk.PhotoImage(img)

label = Label(root, bg='gray')
label.pack(side=LEFT)
label.config(image=frame_image)
label.image = frame_image

root.mainloop()

requirements to use "PyMuPDF-1.21.1" pip install --upgrade pymupdf see more: https://pymupdf.readthedocs.io/