Create Word Document in Python Tkinter [Complete Source Code + Video]

In this Python Tkinter tutorial, we will learn about how to create a word document in python tkinter. We will create an application using Python Tkinter that will generate a word document with dynamic values.

  • Create word document in Python Tkinter – Overview
  • Tkinter Module in Python
  • Python-docx module in Python
  • Overview of the python tkinter application
  • Source code of python tkinter application
  • Output of python tkinter application

Create word document in Python Tkinter

Recently, we got a requirement to generate an experience certificate for employees who are leaving the organization using Python Tkinter.

So we created a complete application using Python Tkinter that will take inputs like below:

User InputsTkinter Widget
Employee IDEntry widget
Employee NameEntry Widget
DesignationEntry Widget
Joining DateEntry Widget
End DateEntry Widget
GenderOptionMenu Widget

Then when the user will fill the form and click on Generate Word button, it will create an experience certificate (word document) with the dynamic values provided by the user.

The word document will also have the company logo, signature, etc.

The form looks like below:

python tkinter application to generate word doc
Application to convert word document in Python Tkinter

The output will come like below:

Create Word Document in Python Tkinter
Create Word Document in Python Tkinter

Also read, How to convert Python file to exe using Pyinstaller

Tkinter Module in Python

Using the Tkinter module in python we can create a graphical user interface (GUI) of any application. It is a popular and easy-to-use python module that can help you convert your command-line-based application into an interactive GUI-based program.

We have a dedicated tutorial on our website for learning Python Tkinter with Examples.

In this section, we will discuss all the python Tkinter widgets that we have used in creating the Tkinter application for generating experience certificate word files.

User InputsTkinter Widget
Employee IDEntry widget
Employee NameEntry Widget
DesignationEntry Widget
Joining DateEntry Widget
End DateEntry Widget
GenderOptionMenu Widget
  • Gender is tkinter OptionMenu widget, user can select the gender using the dropdown. This information is used for declaring subject pronoun.
  • Using gender information, we have specified he, she, him, his, her in the body text of the message.
  • Python Tkinter Entry widget is used to take String based inputs from the user.
  • All other tkinter widgets except gender are python tkinter entry widgets. We have a dedicated blog on Python Tkinter Entry widget and Python Tkinter Optionmenu widget.

Python-docx module in Python

Python-docx module allows us to create word document(s) using python Tkinter. This is a powerful python module that allows the creation of a new word document or updating the existing ones.

Python-docx can be installed using pip and conda package manager with the following command.

# using pip 
pip install python-docx

# using anaconda
conda install -c conda-forge python-docx

Word document has so many features that help the user in writing & formatting the data. Using the python-docx module we can work with all those features. Below is the picture of a word document with marked features.

python tkinter create word document
Word document
  • Each feature has dedicated method in python-docx. Few widely used methods of python-docx are add_paragraph(), add_picture(), add_heading(), add_page_break(), add_table(), etc.
  • First step in the process of creating word document using python is creating word object. All the above methods are the part of the Document object.
from docx import Document

doc = Document()

Moving forward, we will discuss common methods of a python-docx module using which you can create a sample word document in python.

docx.styles()

If you want to save time from manually formatting each row of a word document then you can apply a bundle of pre-formatted styles using this feature in a python-docx module.

The image below shows the styles option on word document:

python tkinter generate word document
Styles in word document
  • Other than this, you can modify the style by adding bullet points, changing font weight to bold, italices, underline, etc.
READ:  How to use Tkinter Filedialog in Python [3 Examples]

Example:

This example, demonstrate how to create style in the python docx module also shows how to use the style on a paragraph in the python docx module.

# style created
new_style = doc.styles['Heading 1']

# style applied
doc.add_paragraph(style=new_style)

docx.add_heading()

Heading specifies the short description of the topic or content. A good heading is always short and self-explanatory. In this section, we will learn how to add heading using python.

  • Every sub-heading is smaller than parent heading and this way they form a heirarchy of 1-9 levels where 1 is the highest level and 9 is the lowest.
  • By default, python-docx picks 1 has the default text for heading and on changing level to 0 changes the category from ‘Heading’ to ‘Title’.
doc.add_heading('United States of America', level=1)
  • Change the level value to modify the heading size in python docx.

docx.add_paragraph()

The paragraph is the widely used method as this will require every time you want to add text on the word document using python module python-docx.

  • Each paragraph adds a single run in the word document using python module python-docx.
  • If you want to add more than one run in a row then use add_run() method on add_paragraph().
  • Method add_run() is very useful when you want to apply two things at the same time. for example, you want to add a paragraph with your country name in bold letters.

Example:

This example demonstrate the use of add_paragraph() method with add_run() method in python-docx module of python.

In this code, we have added a paragraph: ‘Best Country’ and using run object added country name: the United States of America and then applied bold formatting on the country name. This way we have applied 3 activities instead of one, this is the benefit of using the add_run() method.

# one-liner
doc.add_paragraph('Best Country').add_run('United States of America').bold = True

# same thing in 2 lines to make it look good
nomination = doc.add_paragraph('Best Country')
nomination.add_run('United States of America').bold =True
How to create a word document using a python tkinter
Add paragraph in word document using Python docx

docx.add_picture()

Using the add_picture() method in python-docx you can add an image on the word document. The below picture shows the column available for uploading images on a word document.

create a word document using a python tkinter
Add Picture in Word Document using Python
  • Python docx add_picture() methods provides option to add picture in the word file. You can control the size of the image by defining height and width of the image.
  • Heigth and width value can either be in Inches or Centemeters (cm). Inorder to use either of them you have to import Inches or cm from docx.shared.

Syntax:

Height and width are optional to provide but it will be either in Inches or cm (centimeter). We recommend keeping the image in the same folder where the main project is but in case it is not possible then provide the complete path in place of <image_path>.

from docx.shared import Inches

doc = Document()

doc.add_picture(<image_path>, width=Inches(val), height=Inches(val))

Example:

The below example, demonstrate use of docx.add_image() in python docx module. In this example, we have added an image file to the word document.

# import modules
from docx import Document
from docx.shared import Inches

# create an instance 
doc = Document()

# add image
doc.add_picture('logo.png', height=Inches(0.81), width=Inches(2.52))

# save file
doc.save('word.docx')
How to create a word document in Python
Add image in word using python docx

With this, we have concluded a few important and widely used methods of the python docx module. There are many more functions that you can explore on the official website of python-docx.

If you need an explanation of any method or function please write us and we will share the best tutorial for the same.

Read How to make a calculator in Python

Source code of tkinter application

In this section, we have provided source code for creating an application for generating experience certificates for employees who are leaving the organization.

  • In this python application, graphical user interface (GUI) is created using Python library Tkinter.
  • With the interactive interface user can fill in the employee(s) informations like employee id, name, date of joining, etc.
  • The python program will use these information to generate experience certificate in the word format.
PermissionError: [Errno 13] Permission denied: 'word.docx'

Please note: The word file must be closed before clicking on the ‘Generate Word‘ button again. If you are seeing the above permission error that means the file is open. Close the file and try again to fix this error.

READ:  Python Scipy Gamma [10 Useful Examples]

We have provided the source code for:

Python Tkinter Code (GUI Development)

Here is the source code for creating Graphical User Interface (GUI) for the Experience Letter generating application in python.

# modules
from tkinter import *

# clear function
def clear_inputs():
    eid.delete(0, 'end')
    ename.delete(0, 'end')
    desig.delete(0, 'end')
    jd.delete(0, 'end')
    ed.delete(0, 'end')

ws = Tk()
ws.title('Service Certificate Generator')
ws.geometry('400x300')
ws.config(bg='#456')

f = ('sans-serif', 13)
btn_font = ('sans-serif', 10)
bgcolor = '#BF5517'

genvar = StringVar()
genopt = ['Male', 'Female']
genvar.set('Male')

# frames
frame = Frame(ws, padx=20, pady=20, bg=bgcolor)
frame.pack(expand=True, fill=BOTH)


# label widgets
Label(
    frame, 
    text="Employee ID",
    font=f,
    bg=bgcolor
).grid(row=0, column=0, sticky='w')

Label(
    frame,
    text="Employee Name",
    font=f,
    bg=bgcolor
).grid(row=1, column=0, sticky='w')

Label(
    frame,
    text="Designation",
    font=f,
    bg=bgcolor
).grid(row=2, column=0, sticky='w')

Label(
    frame,
    text="Joining Date",
    font=f,
    bg=bgcolor
).grid(row=3, column=0, sticky='w')

Label(
    frame,
    text="End Date",
    font=f,
    bg=bgcolor
).grid(row=4, column=0, sticky='w')

Label(
    frame,
    text='Gender',
    font=f,
    bg=bgcolor
).grid(row=5, column=0, sticky='w')



# entry widgets
eid = Entry(frame, width=20, font=f)
eid.grid(row=0, column=1)

ename = Entry(frame, width=20, font=f)
ename.grid(row=1, column=1)

desig = Entry(frame, width=20, font=f)
desig.grid(row=2, column=1)

jd = Entry(frame, width=20, font=f)
jd.grid(row=3, column=1)

ed = Entry(frame, width=20, font=f)
ed.grid(row=4, column=1)

gender = OptionMenu(
    frame, 
    genvar,
    *genopt
)
gender.grid(row=5, column=1, pady=(5,0))
gender.config(width=15, font=f)
btn_frame = Frame(frame, bg=bgcolor)
btn_frame.grid(columnspan=2, pady=(50, 0))

# default inputs for testing
eid.insert(0,'E1008')
ename.insert(0, 'Vineet Singh')
desig.insert(0, 'Python Developer')
jd.insert(0, 'Aug 3rd, 2020')
ed.insert(0, 'July 31st, 2021')

# action buttons
submit_btn = Button(
    btn_frame,
    text='Generate Word',
    command=None, #generate,
    font=btn_font,
    padx=10, 
    pady=5
)
submit_btn.pack(side=LEFT, expand=True, padx=(15, 0))

clear_btn = Button(
    btn_frame,
    text='Clear',
    command=clear_inputs,
    font=btn_font,
    padx=10, 
    pady=5,
    width=7
)
clear_btn.pack(side=LEFT, expand=True, padx=15)

exit_btn = Button(
    btn_frame,
    text='Exit',
    command=lambda:ws.destroy(),
    font=btn_font,
    padx=10, 
    pady=5
)
exit_btn.pack(side=LEFT, expand=True)

# mainloop
ws.mainloop()

Source code for Creating Word File using Python (command-line)

Here, is the fully functional python source code for creating a word file using python. This code, uses python-docx modules and it do not have GUI that means you have to put the information in the code itself.

# modules
from docx import Document
from docx.opc.coreprops import CoreProperties
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Inches, Pt

# user inputs 
logo = 'files/tsinfo_logo.jpg'
output = 'Experience_letter1.docx'
sign = 'files/signature.png'
ceo_sig_text = '''Adarshnath Singh \nDirector'''
heading = 'Service Certificate'
emp_id = 'E1001' #eid.get() 
emp_name = 'Vineet Singh' # ename.get() 
designation = 'Software Engineer' #desig.get()
joining_date = 'August 20, 2019' #jd.get()
end_date = 'July 31, 2021' #ed.get()

comp_detail = '''TSInfo Technologies (OPC) Pvt Ltd
Flat G-115, SJR Residency, Devarabeesanahalli, Bellandur, Bangalore, 560103
Email: info@tsinfotechnologies.com, Phone: +91-9916854253
'''

gen = 'He' # who.get()


# subject pronoun 
gen2 = 'his' # her
gen3 = 'him' # her

if gen.lower() == 'he':
    gen2 = 'his'
    gen3 = 'him' 
elif gen.lower() == 'she':
    gen2 = 'her' 
    gen3 = 'her'
else:
    print('Error: accept He/She only')

# certificate template
body_text = f'''This is to certify that {emp_name} has worked with TSInfo Technologies (OPC) Pvt Ltd from {joining_date} to {end_date}, and was designated as {designation} at the time of {gen2} leaving the organization.

{gen.capitalize()} is hardworking and a good team player.

We wish {gen3} all the success in his future endeavor.

    '''

# create instance
doc =  Document()

# declare margin
sections = doc.sections
for section in sections:
    section.top_margin = Inches(0.04)
    section.bottom_margin = Inches(0.19)
    section.left_margin = Inches(0.93)
    section.right_margin = Inches(0.89)

section = doc.sections[0]

# logo image placement
logo = doc.add_picture(logo, width=Inches(2.52), height=Inches(0.81))
logo_placement = doc.paragraphs[-1] 
logo_placement.alignment = WD_ALIGN_PARAGRAPH.CENTER

# line space
for _ in range(1):
    linespace_style = doc.styles['Body Text']
    linespace = doc.add_paragraph(style=linespace_style).add_run(' ')
    linespace_style.font.size = Pt(10)

# employee Id
empid_style = doc.styles['Normal']
empid = doc.add_paragraph(style=empid_style).add_run(f'{emp_id}')
empid.font.bold = True

# line space
for _ in range(1):
    linespace_style = doc.styles['Body Text']
    linespace = doc.add_paragraph(style=linespace_style).add_run()
    linespace.font.size = 10

# Header 
heading_style = doc.styles['Body Text']
head=doc.add_paragraph(style=heading_style).add_run(f'{heading}')
doc.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.CENTER
head.font.size = Pt(20)
head.font.bold = True 

# body text 
body_style = doc.styles['Body Text']
body = doc.add_paragraph(style=body_style).add_run(f'{body_text}')
body.font.size = Pt(14)
body.font.name = 'Times New Roman'

#line space
for _ in range(2):
    linespace_style = doc.styles['Body Text']
    linespace = doc.add_paragraph(style=linespace_style).add_run()
    linespace.font.size = 10
  

# signature image & text
ceo_sign = doc.styles['Body Text']
doc.add_picture(sign, width=Inches(1.57), height=Inches(0.43))
doc.add_paragraph(style=ceo_sign).add_run(f'{ceo_sig_text}')
ceo_sign.font.size = Pt(14)
    
# line space
for _ in range(4):
    linespace_style = doc.styles['Body Text']
    linespace = doc.add_paragraph(style=linespace_style)


# footer text : company description
company_text = doc.styles['Normal']
company_text.paragraph_format.space_before = Pt(12)
doc.add_paragraph(style=company_text).add_run(f'{comp_detail}')
center_align = doc.paragraphs[-1] 
center_align.alignment = WD_ALIGN_PARAGRAPH.CENTER

# saving file to word document
doc.save(output)

Read Python Tkinter ToDo List

Complete Source code of creating word document using python tkinter

Here is the source code of the complete application that will generate the experience letter of an employee. It accepts the information through a graphical user interface created using tkinter module in python.

And then, it creates a word document with the provided information. It uses python-docx module to interact with the word document.

Use the following steps to setup the project on your device:

  • Create a folder where you want to keep this project.
  • Create and activate the virtual environment.
  • Install python-docx module in the virtual environment.
  • Create main.py and paste the below code in that file.
  • Create folders with the name files and output. Add images inside the files folder.
  • run the program, Experience Letter will be generated inside the output folder.
# modules
from docx import Document
from docx.opc.coreprops import CoreProperties
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Inches, Pt
from tkinter import *
from tkinter import messagebox


ws = Tk()
ws.title('Service Certificate Generator')
ws.geometry('400x300')
ws.config(bg='#456')

f = ('sans-serif', 13)
btn_font = ('sans-serif', 10)
bgcolor = '#BF5517'

genvar = StringVar()
genopt = ['Male', 'Female']
genvar.set('Male')

def clear_inputs():
    eid.delete(0, 'end')
    ename.delete(0, 'end')
    desig.delete(0, 'end')
    jd.delete(0, 'end')
    ed.delete(0, 'end')
    


def generate():

     # data variables
    logo = 'files/tsinfo_logo.jpg'
    output = 'output/Experience_letter.docx'
    sign = 'files/signature.png'
    ceo_sig_text = '''Adarshnath Singh \nDirector'''
    heading = 'Service Certificate'
    emp_id = eid.get() 
    emp_name = ename.get() 
    designation = desig.get()
    joining_date = jd.get()
    end_date = ed.get()

    comp_detail = '''
    TSInfo Technologies (OPC) Pvt Ltd
    Flat G-115, SJR Residency, Devarabeesanahalli, Bellandur, Bangalore, 560103
    Email: info@tsinfotechnologies.com, Phone: +91-9916854253
    '''
    # gender specification 

    gen1 = 'He' # she
    gen2 = 'his' # her
    gen3 = 'him' # her

    if genvar.get() == 'Male':
        gen1 = 'He'
        gen2 = 'his'
        gen3 = 'him' 
    elif genvar.get() == 'Female':
        gen1 = 'She'
        gen2 = 'her' 
        gen3 = 'her'
    else:
        messagebox.showerror('Error', 'Incorrect gender Selection!')

    # experience certificate template
    body_text = f'''
This is to certify that {emp_name} has worked with TSInfo Technologies (OPC) Pvt Ltd from {joining_date} to {end_date}, and was designated as {designation} at the time of {gen2} leaving the organization.

{gen1} is hardworking and a good team player.

We wish {gen3} all the success in {gen2} future endeavor.

    '''

    # create object(s)
    doc =  Document()
    sections = doc.sections


   # declare margin
    for section in sections:
        section.top_margin = Inches(0.04)
        section.bottom_margin = Inches(0.19)
        section.left_margin = Inches(0.93)
        section.right_margin = Inches(0.89)

    section = doc.sections[0]


    # logo image placement
    logo = doc.add_picture(logo, width=Inches(2.52), height=Inches(0.81))
    logo_placement = doc.paragraphs[-1] 
    logo_placement.alignment = WD_ALIGN_PARAGRAPH.CENTER

    # line space
    for _ in range(1):
        linespace_style = doc.styles['Body Text']
        linespace = doc.add_paragraph(style=linespace_style).add_run(' ')
        linespace_style.font.size = Pt(10)


    # employee Id
    empid_style = doc.styles['Normal']
    empid = doc.add_paragraph(style=empid_style).add_run(f'{emp_id}')
    empid.font.bold = True

    # line space
    for _ in range(1):
        linespace_style = doc.styles['Body Text']
        linespace = doc.add_paragraph(style=linespace_style).add_run()
        linespace.font.size = 10

    # Header 
    heading_style = doc.styles['Body Text']
    head = doc.add_paragraph(style=heading_style).add_run(f'{heading}')
    doc.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.CENTER
    head.font.size = Pt(20)
    head.font.bold = True 


    # body text 
    body_style = doc.styles['Body Text']
    body = doc.add_paragraph(style=body_style).add_run(f'{body_text}')
    body.font.size = Pt(14)
    body.font.name = 'Times New Roman'

    #line space
    for _ in range(2):
        linespace_style = doc.styles['Body Text']
        linespace = doc.add_paragraph(style=linespace_style).add_run()
        linespace.font.size = 10
  


    # signature image & text
    ceo_sign = doc.styles['Body Text']
    doc.add_picture(sign, width=Inches(1.57), height=Inches(0.43))
    doc.add_paragraph(style=ceo_sign).add_run(f'{ceo_sig_text}')
    ceo_sign.font.size = Pt(14)
    


    # line space
    for _ in range(4):
        linespace_style = doc.styles['Body Text']
        linespace = doc.add_paragraph(style=linespace_style)
        # linespace.font.size = Pt(10)

    # footer text : company description
    company_text = doc.styles['Normal']
    company_text.paragraph_format.space_before = Pt(12)
    doc.add_paragraph(style=company_text).add_run(f'{comp_detail}')
    center_align = doc.paragraphs[-1] 
    center_align.alignment = WD_ALIGN_PARAGRAPH.CENTER

    doc.save(output)

# frames
frame = Frame(ws, padx=20, pady=20, bg=bgcolor)
frame.pack(expand=True, fill=BOTH)



# label widgets
Label(
    frame, 
    text="Employee ID",
    font=f,
    bg=bgcolor
).grid(row=0, column=0, sticky='w')

Label(
    frame,
    text="Employee Name",
    font=f,
    bg=bgcolor
).grid(row=1, column=0, sticky='w')

Label(
    frame,
    text="Designation",
    font=f,
    bg=bgcolor
).grid(row=2, column=0, sticky='w')

Label(
    frame,
    text="Joining Date",
    font=f,
    bg=bgcolor
).grid(row=3, column=0, sticky='w')

Label(
    frame,
    text="End Date",
    font=f,
    bg=bgcolor
).grid(row=4, column=0, sticky='w')

Label(
    frame,
    text='Gender',
    font=f,
    bg=bgcolor
).grid(row=5, column=0, sticky='w')



# entry widgets
eid = Entry(frame, width=20, font=f)
eid.grid(row=0, column=1)

ename = Entry(frame, width=20, font=f)
ename.grid(row=1, column=1)

desig = Entry(frame, width=20, font=f)
desig.grid(row=2, column=1)

jd = Entry(frame, width=20, font=f)
jd.grid(row=3, column=1)

ed = Entry(frame, width=20, font=f)
ed.grid(row=4, column=1)

gender = OptionMenu(
    frame, 
    genvar,
    *genopt
)
gender.grid(row=5, column=1, pady=(5,0))
gender.config(width=15, font=f)


btn_frame = Frame(frame, bg=bgcolor)
btn_frame.grid(columnspan=2, pady=(50, 0))

# default inputs for testing
eid.insert(0,'E1008')
ename.insert(0, 'Vineet Singh')
desig.insert(0, 'Python Developer')
jd.insert(0, 'Aug 3rd, 2020')
ed.insert(0, 'July 31st, 2021')



submit_btn = Button(
    btn_frame,
    text='Generate Word',
    command=generate,
    font=btn_font,
    padx=10, 
    pady=5
)
submit_btn.pack(side=LEFT, expand=True, padx=(15, 0))

clear_btn = Button(
    btn_frame,
    text='Clear',
    command=clear_inputs,
    font=btn_font,
    padx=10, 
    pady=5,
    width=7
)
clear_btn.pack(side=LEFT, expand=True, padx=15)

exit_btn = Button(
    btn_frame,
    text='Exit',
    command=lambda:ws.destroy(),
    font=btn_font,
    padx=10, 
    pady=5
)
exit_btn.pack(side=LEFT, expand=True)


# mainloop
ws.mainloop()

Read Python Tkinter Canvas

READ:  Matplotlib time series plot

Output of Python Tkinter Application

In this output, there is a form that accepts various information about an employee. Once information is filled, on clicking the ‘Generate Word’ button a word file will be generated.

That word file will have a template of experience certificate with the employee information (Id, name, joining date, etc) dynamically allocated at the respective place.

  • Clear button will clear the enteries and exit button will terminate the program.
  • This application form is created using python tkinter and it is using python-docx module to interact with the word file.
python tkinter application to generate word doc
Python Tkinter Service Certificate Generator
  • Below is the picture of generated service certificate. This is a word file with dynamic values highlighted in yellow. All these yellow values are provided by the user in the above image.
  • highlighted yellow is for demonstration purpose only, while executing the program this won’t appear.
How to create a word document in Python
Python Tkinter Generated Service Certificate

This is how to create a word document in Python by using Python Tkinter.

Related Python Tkinter tutorials: