Table of Contents
Output
in conclusion
Home Backend Development Python Tutorial How to add PDF in Tkinter GUI Python?

How to add PDF in Tkinter GUI Python?

Sep 08, 2023 am 08:29 AM

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
Copy after login

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

import fitz
from tkinter import *
from PIL import Image, ImageTk
Copy after login

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)
Copy after login

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)
Copy after login

Let’s also count the number of pages -

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

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)
Copy after login

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)
Copy after login
# add a label for the entry point
label = Label(root, text="Enter page number to display:")
Copy after login

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)
Copy after login

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
Copy after login

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)
Copy after login

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)
Copy after login

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

entry.insert(0, '1')
show_image()
Copy after login

We configure the scroll bar

scrollbar.config(command = canvas.yview)
root.mainloop()
Copy after login

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

doc.close()
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

See all articles