如何将Tkinter Text组件的文本发送至打印机打印?
实现Tkinter文本编辑器的打印功能
嘿,我之前刚好给Tkinter文本编辑器做过打印功能,给你分享几个实用的实现方案,能帮你达到类似Word的打印效果!
方法一:跨平台基础版(利用系统打印工具)
这个方案不用额外装库,靠Tkinter和系统自带的打印命令就能实现,适合快速上手:
首先在你的编辑器代码里添加这个打印函数:
import tkinter as tk import subprocess import os from tkinter import filedialog class TextEditor: def __init__(self, root): self.root = root self.text_widget = tk.Text(root) self.text_widget.pack(fill=tk.BOTH, expand=True) # 添加打印按钮 print_btn = tk.Button(root, text="打印", command=self.print_document) print_btn.pack() def print_document(self): # 获取文本框里的所有内容 content = self.text_widget.get("1.0", tk.END) # 弹出保存对话框(其实是用来触发系统打印流程) temp_file = filedialog.asksaveasfilename( defaultextension=".txt", filetypes=[("文本文件", "*.txt"), ("所有文件", "*.*")] ) if not temp_file: return # 把内容写入临时文件 with open(temp_file, 'w', encoding='utf-8') as f: f.write(content) # 根据系统调用对应的打印命令 if os.name == 'nt': # Windows系统用记事本打印 subprocess.run(["notepad.exe", "/p", temp_file]) elif os.name == 'posix': # Linux/macOS用系统打印命令 subprocess.run(["lpr", temp_file]) # 打印完成后删掉临时文件(可选) os.remove(temp_file)
这个方法的好处是不用额外依赖,缺点是排版比较简单,和记事本打印效果一致。
方法二:Windows平台专属优化(更贴近Word体验)
如果你的应用主要在Windows上跑,用pywin32库可以直接控制打印机,实现更精细的打印排版,比如设置字体、打印方向:
先安装依赖:
pip install pywin32
然后实现打印函数:
import win32print import win32ui from win32con import DM_ORIENTATION, DMORIENT_PORTRAIT def print_document(self): content = self.text_widget.get("1.0", tk.END) # 获取默认打印机 printer_name = win32print.GetDefaultPrinter() # 打开打印机连接 hprinter = win32print.OpenPrinter(printer_name) try: # 获取并设置打印机属性(比如纵向打印) properties = win32print.GetPrinter(hprinter, 2) devmode = properties['pDevMode'] devmode.DM_ORIENTATION = DMORIENT_PORTRAIT win32print.SetPrinter(hprinter, 2, properties, 0) # 创建打印设备上下文 hdc = win32ui.CreateDC() hdc.CreatePrinterDC(printer_name) # 开始打印作业 hdc.StartDoc("我的Tk编辑器打印任务") hdc.StartPage() # 设置打印字体(这里用宋体12号) font = win32ui.CreateFont({ "name": "SimSun", "height": 12*20, # 20是Windows字体的缩放因子 "weight": 400, }) hdc.SelectObject(font) # 逐行绘制文本,处理分页 y_pos = 50 # 页面起始Y坐标 line_height = 15*20 # 行间距 lines = content.split('\n') for line in lines: if y_pos > hdc.GetDeviceCaps(1): # 超过页面高度就分页 hdc.EndPage() hdc.StartPage() y_pos = 50 hdc.TextOut(50, y_pos, line) y_pos += line_height # 结束打印 hdc.EndPage() hdc.EndDoc() finally: # 关闭打印机连接,避免资源泄漏 win32print.ClosePrinter(hprinter)
这个方案能直接控制打印的细节,体验更接近Word,但只支持Windows系统。
方法三:跨平台通用方案(生成PDF再打印)
如果需要同时支持Windows、Linux和macOS,生成PDF后调用系统打印PDF的工具是最优解,还能支持更复杂的排版。这里用reportlab库来生成PDF:
先安装依赖:
pip install reportlab
然后实现打印函数:
from reportlab.pdfgen import canvas import subprocess import os import tempfile import time import sys def print_document(self): content = self.text_widget.get("1.0", tk.END) # 创建临时PDF文件(打印完成后自动删除) with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp_file: pdf_path = tmp_file.name # 生成PDF内容 pdf_canvas = canvas.Canvas(pdf_path) pdf_canvas.setFont("Helvetica", 12) y_pos = 750 # PDF页面的起始Y坐标(从底部往上算) line_height = 15 lines = content.split('\n') for line in lines: # 超过页面底部就新建一页 if y_pos < 50: pdf_canvas.showPage() pdf_canvas.setFont("Helvetica", 12) y_pos = 750 pdf_canvas.drawString(50, y_pos, line) y_pos -= line_height pdf_canvas.save() # 调用系统打印工具打开并打印PDF if os.name == 'nt': # Windows用默认PDF阅读器打印 subprocess.run(["start", "", "/wait", pdf_path], shell=True) elif os.name == 'posix': if sys.platform == 'darwin': # macOS用预览打印 subprocess.run(["open", "-a", "Preview", "-P", pdf_path]) else: # Linux用lp命令打印 subprocess.run(["lp", pdf_path]) # 给系统打印工具留时间读取文件,再删除临时文件 time.sleep(2) os.remove(pdf_path)
这个方案完全跨平台,还能扩展支持字体样式、页眉页脚等复杂排版,适合需要多平台兼容的场景。
内容的提问来源于stack exchange,提问作者Delalie Rawllings
相关产品推荐
相关产品推荐

