search
HomeBackend DevelopmentPython TutorialHow to add PDF in Tkinter GUI Python?

This article will teach us how to display PDF files in Tkinter GUI. We will use the PyMuPDF library to read the pdf file and convert it to an image, and then use Tkinter to display the image.

For our task we will perform the following steps -

  • Read PDF files.

  • Define a transformation matrix to be applied to the PDF page to obtain the image.

  • Calculate the total number of pages for error checking.

  • Define the screen (canvas) of the GUI.

  • Define a helper function for converting PDF pages to PIL images.

  • Define a function to display a page image in the GUI.

  • Add buttons, labels, scroll bars, etc. and configure them.

First, we first run the following command in the terminal to install the PyMuPDF package.

python -m pip install --upgrade pip
python -m pip install --upgrade pymupdf

Now we need to import the libraries we will use. Import Fitz

import fitz
from tkinter import *
from PIL import Image, ImageTk

Here fitz is a utility library provided with the PyMuPDF library for getting PDF pages as images.

We first use the fitz.open function to open the PDF file to be displayed in the GUI. This returns a document object that can be used to access the page.

# open pdf file
file_name = "sample.pdf"
doc = fitz.open(file_name)

Now we need to specify how to view the page. By defining the matrix function below, we can "fitz" to maintain 1x scaling.

# transformation matrix we can apply on pages
zoom = 1
mat = fitz.Matrix(zoom, zoom)

Let’s also count the number of pages -

# count number of pages
num_pages = 0
for p in doc:
num_pages += 1

Now we will define a screen, add a scrollbar and a canvas to our code -

# initialize and set screen size
root = Tk()
root.geometry('750x700')

# add scroll bar
scrollbar = Scrollbar(root)
scrollbar.pack(side = RIGHT, fill = Y)

# add canvas
canvas = Canvas(root, yscrollcommand = scrollbar.set)
canvas.pack(side = LEFT, fill = BOTH, expand = 1)

Here our screen is represented by the name "root" and has dimensions of 750x700. We also added a scrollbar and specified that it be on the right and fill the entire height. Again, we add the canvas to the left and fill the entire screen on both sides!

In order to receive the page number that the user wants to read, we need the page number as input. We can do this -

# define entry point (field for taking inputs)
entry = Entry(root)
# add a label for the entry point
label = Label(root, text="Enter page number to display:")

The parameter "root" tells us that these objects will be associated with the screen "root".

Now we will define a helper function to get the image of the PDF file from the page number.

def pdf_to_img(page_num):
page = doc.load_page(page_num)
pix = page.get_pixmap(matrix=mat)
return Image.frombytes("RGB", [pix.width, pix.height], pix.samples)

Here we first use doc.load_page to load the page and pass the page number as a parameter. We then convert the PDF page to get the pixel representation of the page in the second line. Finally, we convert the pixel representation to PIL image format.

Now we define a function show_image to display images in the Tkinter GUI.

def show_image():
try:
page_num = int(entry.get()) - 1
assert page_num >= 0 and page_num < num_pages
im = pdf_to_img(page_num)
img_tk = ImageTk.PhotoImage(im)
frame = Frame(canvas)
panel = Label(frame, image=img_tk)
panel.pack(side="bottom", fill="both", expand="yes")
frame.image = img_tk
canvas.create_window(0, 0, anchor='nw', window=frame)
frame.update_idletasks()
canvas.config(scrollregion=canvas.bbox("all"))
except:
pass

First, we read the page number from the previously defined entry point and convert it to an integer. If it is not a valid integer, an exception occurs and the exception block handles it. We then check if the page number is between 0 or the number of pages, since this is the only valid page range we can display. Then using the helper function we defined earlier, we get the PIL image of the user-specified page. We then set up the frame, panel, and canvas to display the image correctly.

Next we add a button to display the page. We pass the function "show_image" as a command. So whenever the button is pressed, the "show_image" function is called.

# add button to display pages
button = Button(root, text="Show Page", command=show_image)

Now we set the visual position of the various components defined previously -

# set visual locations
label.pack(side=TOP, fill=None)
entry.pack(side=TOP, fill=BOTH)
button.pack(side=TOP, fill=None)

We also set the initial page to the first page of the PDF, as follows -

entry.insert(0, '1')
show_image()

We configure the scroll bar

scrollbar.config(command = canvas.yview)
root.mainloop()

Finally we close the PDF to avoid it being damaged by our computer.

doc.close()

Output

After running the program we will see the following output!

如何在Tkinter GUI Python中添加PDF?

in conclusion

This article teaches us how to use the PyMuPDF library with Pillow and Tkinter to display PDF files in the Tkinter GUI. We also learned how to count pages, convert PDF pages to images, make interactive buttons, and how to visually place the different elements that make up a GUI.

The above is the detailed content of How to add PDF in Tkinter GUI Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
What are some common reasons why a Python script might not execute on Unix?What are some common reasons why a Python script might not execute on Unix?Apr 28, 2025 am 12:18 AM

The reasons why Python scripts cannot run on Unix systems include: 1) Insufficient permissions, using chmod xyour_script.py to grant execution permissions; 2) Shebang line is incorrect or missing, you should use #!/usr/bin/envpython; 3) The environment variables are not set properly, and you can print os.environ debugging; 4) Using the wrong Python version, you can specify the version on the Shebang line or the command line; 5) Dependency problems, using virtual environment to isolate dependencies; 6) Syntax errors, using python-mpy_compileyour_script.py to detect.

Give an example of a scenario where using a Python array would be more appropriate than using a list.Give an example of a scenario where using a Python array would be more appropriate than using a list.Apr 28, 2025 am 12:15 AM

Using Python arrays is more suitable for processing large amounts of numerical data than lists. 1) Arrays save more memory, 2) Arrays are faster to operate by numerical values, 3) Arrays force type consistency, 4) Arrays are compatible with C arrays, but are not as flexible and convenient as lists.

What are the performance implications of using lists versus arrays in Python?What are the performance implications of using lists versus arrays in Python?Apr 28, 2025 am 12:10 AM

Listsare Better ForeflexibilityandMixdatatatypes, Whilearraysares Superior Sumerical Computation Sand Larged Datasets.1) Unselable List Xibility, MixedDatatypes, andfrequent elementchanges.2) Usarray's sensory -sensical operations, Largedatasets, AndwhenMemoryEfficiency

How does NumPy handle memory management for large arrays?How does NumPy handle memory management for large arrays?Apr 28, 2025 am 12:07 AM

NumPymanagesmemoryforlargearraysefficientlyusingviews,copies,andmemory-mappedfiles.1)Viewsallowslicingwithoutcopying,directlymodifyingtheoriginalarray.2)Copiescanbecreatedwiththecopy()methodforpreservingdata.3)Memory-mappedfileshandlemassivedatasetsb

Which requires importing a module: lists or arrays?Which requires importing a module: lists or arrays?Apr 28, 2025 am 12:06 AM

ListsinPythondonotrequireimportingamodule,whilearraysfromthearraymoduledoneedanimport.1)Listsarebuilt-in,versatile,andcanholdmixeddatatypes.2)Arraysaremorememory-efficientfornumericdatabutlessflexible,requiringallelementstobeofthesametype.

What data types can be stored in a Python array?What data types can be stored in a Python array?Apr 27, 2025 am 12:11 AM

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

What happens if you try to store a value of the wrong data type in a Python array?What happens if you try to store a value of the wrong data type in a Python array?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Which is part of the Python standard library: lists or arrays?Which is part of the Python standard library: lists or arrays?Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function