首页 > 解决方案 > 如何在单独的运行中更改字体

问题描述

我尝试在单次运行中更改格式,而不使用根据文档https://python-docx.readthedocs.io/en/latest/user/text.html的样式

我不知道为什么,但下面的例子并没有改变它。

import os, sqlite3
import tkinter as tk
from tkinter import ttk, Menu
from docx import Document
from docx.shared import Pt

def create_offer():
    offer = Document()
    p = offer.add_paragraph("Just a paragraph")
    run = offer.add_paragraph("Test run").add_run()
    font = run.font
    font.name = 'Calibri'
    font.bold = True
    font.size = Pt(12)
    run = offer.add_paragraph("2nd test run").add_run()
    offer.save("Demo.docx")

提前致谢

标签: pythonpython-docx

解决方案


您应该将要格式化的文本添加为add_run()​​函数中的参数,而不是add_paragraph()函数。

然后你的create_offer函数看起来像

from docx import Document
from docx.shared import Pt

def create_offer():
    offer = Document()
    p = offer.add_paragraph("Just a paragraph")
    run = offer.add_paragraph().add_run("Test run")
    font = run.font
    font.name = 'Calibri'
    font.bold = True
    font.size = Pt(12)
    run = offer.add_paragraph().add_run("2nd test run")
    offer.save("Demo.docx")

推荐阅读