You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python为终端(控制台)添加背景图片

如何用Python给控制台窗口添加背景图片

普通原生控制台(比如Windows CMD、Linux终端)本身不直接支持设置背景图片,要实现你需要的效果,得根据不同平台借助系统API或第三方工具来实现,以下是分平台的具体方案:

Windows平台方案

Windows控制台可通过调用系统API直接设置背景,这里提供两种实现方式:

方法1:用Python自带的ctypes调用Windows API

无需额外安装库,直接调用系统接口,仅支持BMP格式图片:

import ctypes
from ctypes import wintypes

user32 = ctypes.WinDLL('user32', use_last_error=True)
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

# 定义API函数的参数和返回类型
HWND = wintypes.HWND
HDC = wintypes.HDC
LPCSTR = wintypes.LPCSTR

user32.GetDC.restype = HDC
user32.GetDC.argtypes = (HWND,)
user32.ReleaseDC.restype = wintypes.BOOL
user32.ReleaseDC.argtypes = (HWND, HDC)
kernel32.LoadImageA.restype = wintypes.HANDLE
kernel32.LoadImageA.argtypes = (wintypes.HINSTANCE, LPCSTR, wintypes.UINT, wintypes.INT, wintypes.INT, wintypes.UINT)

IMAGE_BITMAP = 0
LR_LOADFROMFILE = 0x00000010

def set_console_background(image_path):
    console_handle = kernel32.GetConsoleWindow()
    dc = user32.GetDC(console_handle)
    # 加载BMP图片
    hbitmap = kernel32.LoadImageA(None, image_path, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE)
    if not hbitmap:
        raise ctypes.WinError(ctypes.get_last_error())
    try:
        old_obj = user32.SelectObject(dc, hbitmap)
        user32.UpdateWindow(console_handle)
        user32.SelectObject(dc, old_obj)
    finally:
        user32.DeleteObject(hbitmap)
        user32.ReleaseDC(console_handle, dc)

# 使用示例
if __name__ == "__main__":
    set_console_background("你的背景图.bmp")
    input("按回车键退出...")

方法2:用pywin32库简化操作

先安装依赖库:

pip install pywin32

再用以下代码实现(支持BMP格式,可自动适配窗口尺寸):

import win32gui
import win32api
import win32con
import win32ui

def set_console_background(image_path):
    hwnd = win32gui.GetConsoleWindow()
    hdc = win32gui.GetDC(hwnd)
    mem_dc = win32ui.CreateDCFromHandle(hdc)
    bmp = win32ui.LoadBitmap(image_path)
    
    # 获取窗口尺寸并拉伸图片适配
    rect = win32gui.GetWindowRect(hwnd)
    width = rect[2] - rect[0]
    height = rect[3] - rect[1]
    mem_dc.StretchBlt((0, 0), (width, height), bmp.GetDC(), (0, 0), bmp.GetWidth(), bmp.GetHeight(), win32con.SRCCOPY)
    
    # 释放资源
    bmp.DeleteDC()
    mem_dc.DeleteDC()
    win32gui.ReleaseDC(hwnd, hdc)
    win32gui.UpdateWindow(hwnd)

# 使用示例
if __name__ == "__main__":
    set_console_background("你的背景图.bmp")
    input("按回车键退出...")

Linux/macOS平台方案

原生终端不支持直接设置图片背景,可通过以下两种方式实现类似效果:

方法1:利用终端模拟器的内置功能

现代终端模拟器(比如iTerm2、Konsole、GNOME Terminal)都自带背景图片设置功能,直接在终端的设置面板里配置即可。如果需要Python自动化配置,可修改终端的配置文件:

  • iTerm2:修改~/Library/Application Support/iTerm2/DynamicProfiles/下的JSON配置文件
  • Konsole:修改~/.local/share/konsole/下的.profile文件,调整BackgroundImage字段

方法2:用curses库模拟图片背景

将图片转换成灰度ASCII字符,模拟背景效果,支持常见图片格式:
先安装依赖:

pip install pillow curses

实现代码:

import curses
from PIL import Image

def draw_background(stdscr, image_path):
    height, width = stdscr.getmaxyx()
    # 调整图片尺寸适配终端窗口
    img = Image.open(image_path).resize((width, height))
    img_gray = img.convert("L")
    # 灰度对应的ASCII字符集
    chars = " .:-=+*#%@"
    
    # 逐行绘制背景
    for y in range(height):
        for x in range(width):
            if x >= width or y >= height:
                continue
            gray = img_gray.getpixel((x, y))
            char = chars[gray // 25]
            stdscr.addch(y, x, char, curses.color_pair(0))
    stdscr.refresh()

def main(stdscr):
    curses.start_color()
    curses.use_default_colors()
    draw_background(stdscr, "你的背景图.jpg")
    # 在背景上叠加文字
    stdscr.addstr(5, 5, "这是背景上的文字", curses.A_BOLD)
    stdscr.getch()

if __name__ == "__main__":
    curses.wrapper(main)

内容的提问来源于stack exchange,提问作者lunix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 02:35:32