首页 > 解决方案 > 在打印机上打印整个窗口的 Tkinter 程序

问题描述

我正在 Raspberry Pi 3B + 上编写 Python3 程序。我使用 Tkinter 作为 GUI。

现在,我想编写一个程序,通过按下窗口上的按钮在打印机上打印整个窗口。我已经安装了 CUP 并且可以使用其他标准应用程序进行打印。

程序如下,但是按下按钮时会出现错误信息。我现在该怎么办?

错误信息:

Exception in Tkinter callback
Traceback (most recent call last):
 File “/usr/lib/python3.y/tkinter/__init__.py”, Line 1705, in __call__
  return self.func(゛args)
 File "/home/pi/Projects/tk.py", line 19, in printer
   img.save(buf, 'PNG’)
 Fi!e "/usr/lib/python3/dist-packages/PlL/lmage・py”, line 1994, in save・
   save_handler(self, fp, filename
  File "/usr/lib/python3/dist-packages/PIL/PngImagePlugin.py" ,line 773, in _save
   fp.write(_MAGIC)
  TypeError: string argument expected, 90t 'bytes'

源代码

#!/usr/bin/python3
#-*- coding: utf8 -*-
import tkinter as tk
import sys
import subprocess
from PIL import Image
import io

def printer():
    buf = io.StringIO()
    screen = (500, 500)
    bgcolor = (0x00, 0x00, 0x00)
    img = Image.new('RGB', screen, bgcolor)
    img.save(buf, 'PNG')
    p = subprocess.Popen('lp', stdin=subprocess.PIPE)
    p.communicate(buf.getvalue())
    p.stdin.close()
    buf.close()

root = tk.Tk()
root.attributes('-type','splash')
root.geometry("800x480")
button = tk.Button(root,text="閉じる",command=sys.exit)
button.pack()
button2 = tk.Button(root,text="印刷",command=printer)
button2.pack()
root.mainloop()

标签: pythontkinterprinting

解决方案


推荐阅读