如何通过tkinter中的本地或网络打印机进行打印

时间:2017-09-04 16:38:45

标签: python tkinter printing textbox printers

我想在我的计算机上选择一台已安装的打印机并通过它进行打印,但我的组合框不会在我的机器上显示打印机,而是在我的IDE中打印到我的终端。

已经尝试了几天,并且已经解决了这个问题。在阅读完之后已经安装了win32print模块。我的代码如下:

from tkinter import *
from tkinter import ttk
import win32print



def installed_printer():
    printers = win32print.EnumPrinters(2)
      for p in printers:
         return(p)



def locprinter():
    pt = Toplevel()
    pt.geometry("250x250")
    pt.title("choose printer")
    LABEL = Label(pt, text="select Printer").pack()
    PRCOMBO = ttk.Combobox(pt, width=35, 
    textvariable=installed_printer).pack()
    BUTTON = ttk.Button(pt, text="refresh", 
    command=installed_printer).pack()


root = Tk()
root.title("printer selection in tkinter")
root.geometry("400x400")


menubar = Menu(root)
root.config(menu=menubar)

file_menu = Menu(menubar)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="printer", command=locprinter)


LAB = Label(root, text="Comment")
T2 = Text(root, width=40, height=10)


def INFO():
print(T2.get("1.0", END))


Print_Button = Button(root, text ="Print", command = 
INFO).place(x=180,y=250)

LAB.pack()
T2.pack()

root.mainloop()

我如何实现这一点,因为我想用tkinter框架在我的文本框中打印内容。

1 个答案:

答案 0 :(得分:0)

这是你想要创造的吗?

    from tkinter import *
from tkinter import ttk
import win32api
import win32print
import tempfile



def installed_printer():
    printers = win32print.EnumPrinters(2)
    for p in printers:
        return(p)

printerdef = ''

def locprinter():
    pt = Toplevel()
    pt.geometry("250x250")
    pt.title("choose printer")
    var1 = StringVar()
    LABEL = Label(pt, text="select Printer").pack()
    PRCOMBO = ttk.Combobox(pt, width=35,textvariable=var1)
    print_list = []
    printers = list(win32print.EnumPrinters(2))
    for i in printers:
        print_list.append(i[2])
    print(print_list)
    # Put printers in combobox
    PRCOMBO['values'] = print_list
    PRCOMBO.pack()
    def select():
        global printerdef
        printerdef = PRCOMBO.get()
        pt.destroy()
    BUTTON = ttk.Button(pt, text="Done",command=select).pack()

root = Tk()
root.title("printer selection in tkinter")
root.geometry("400x400")


menubar = Menu(root)
root.config(menu=menubar)

file_menu = Menu(menubar)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="printer", command=locprinter)


LAB = Label(root, text="Comment")
T2 = Text(root, width=40, height=10, wrap=WORD)


def INFO():
    printText = T2.get("1.0", END)
    print(printText)
    print(printerdef)
    filename = tempfile.mktemp(".txt")
    open(filename, "w").write(printText)
    # Bellow is call to print text from T2 textbox
    win32api.ShellExecute(
        0,
        "printto",
        filename,
        '"%s"' % win32print.GetDefaultPrinter(),
        ".",
        0
    )


Print_Button = Button(root, text ="Print", command=INFO).place(x=180,y=250)

LAB.pack()
T2.pack()

root.mainloop()