0

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!-

  • The variable `frame` is discarded and garbage collected after the function ends so `timg` is also garbage collected. Try defining `frame = []` outside of the function or add `text_1.tk_img = timg` – TheLizzard May 06 '21 at 17:28
  • It is almost certainly related to this: https://stackoverflow.com/questions/16424091 – Bryan Oakley May 06 '21 at 17:43
  • @BryanOakley I think you are right but OP tried putting the `PhotoImage`s in a list but the list goes out of scope as well. – TheLizzard May 06 '21 at 17:48
  • Its working now! Now I understand the mistakes, thanks for the replies. @TheLizzard – Lee hua Wei May 07 '21 at 02:02

1 Answers1

0

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/

impactro
  • 564
  • 4
  • 7
  • Please add some explanation to your code, and explain how it differs from the code in the question. Code-only answer are low value and likely to be removed. – miken32 Jan 09 '23 at 20:56