'How to fill the textbox background color using Python-pptx?

I am using Python-pptx to create ppt, i want to fill the textbox background with other color.

from pptx import Presentation
from pptx.util import Inches, Pt
from datetime import datetime
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN

prs = Presentation()
prs.slide_width = Inches(16)
prs.slide_height = Inches(9)
blank_slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(blank_slide_layout)

slide_layout = prs.slide_layouts[5]
slide2 = prs.slides.add_slide(slide_layout)

title_textbox = slide.shapes.add_textbox(Inches(5), Inches(0.4), Inches(6), Inches(0.6))
title = title_textbox.text_frame

pic = slide.shapes.add_picture('image_name.jpg', Inches(3.8), Inches(1.3), Inches(8.5), Inches(6))

subtitle_textbox = slide.shapes.add_textbox(Inches(5), Inches(7.5), Inches(6), Inches(1))
subtitle = subtitle_textbox.text_frame


Solution 1:[1]

I am not 100% sure if I got your question correctly. You want to create a textbox and color it?

I changed it a bit:

from pptx import Presentation
from pptx.util import Inches
from pptx.dml.color import RGBColor

prs = Presentation()
prs.slide_width = Inches(16)
prs.slide_height = Inches(9)
blank_slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(blank_slide_layout)

textbox = slide.shapes.add_textbox(Inches(5), Inches(0.4), Inches(6), Inches(5))

textbox.text_frame.text = "foo"
textbox.fill.solid()
textbox.fill.fore_color.rgb = RGBColor(255, 0, 0)

This creates a textbox with text "foo" and red color. You can find more options for the manipulation of your shape here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Irgendniemand