在通过 Python 脚本将数据从 TKinter 传递到 Photoshop 时,如何解决无法识别的字符问题?

问题描述

我制作了一个 GUI 应用程序,如下所示:

A picture of my GUI

红色的是Tkinter Text widgets,黄色的是Tkinter Entry widgets

接受用户输入后,数据将被添加到 PSD 文件中,然后渲染为图像。但是可以说,在将以下数据作为输入后:

Filled Data

它渲染以下 Photoshop 文件

Generated Prescription

如何解决无法正确识别 "\n" 从而导致呈现的文档无用的问题。

以下代码用于将接受的用户数据转换为字符串,然后将其添加到 Photoshop 模板中,然后进行渲染:

def DataAdder2CSV():
    global edate,eSNO,eage,egender,ename,ePID,econtact,ecomp,eallergy,ehistory,eR
    e=edate.get()
    a=eSNO.get()
    d=eage.get()
    f=egender.get()
    b=ename.get()
    c=ePID.get()
    g=econtact.get()
    h=ecomp.get(1.0,END)
    i=eallergy.get(1.0,END)
    j=ehistory.get(1.0,END)
    k=eR.get(1.0,END)
    data=[a,b,c,d,e,f,g,h,i,j,k]
       
    file=open("Patient_Data.csv","a",newline="")
    writer=csv.writer(file,delimiter=",")

    writer.writerow(data)

    file.close()
    messageBox.showinfo("Prescription Generator","Data has been saved to the database successfully!")
    import win32com.client,os
    objShell = win32com.client.dispatch("WScript.Shell")
    UserDocs = objShell.SpecialFolders("MyDocuments")
    from tkinter import filedialog

    ExpDir=filedialog.askdirectory(initialdir=UserDocs,title="Choose Destination Folder")

    psApp = win32com.client.dispatch("Photoshop.Application")
    psApp.Open("D:\Coding\Python Scripts\Dr Nikhil Prescription App\Prescription Generator\Presc_Template.psd")
    doc = psApp.Application.ActiveDocument

    lf1 = doc.ArtLayers["name"]
    tol1 = lf1.TextItem
    tol1.contents = b

    lf2 = doc.ArtLayers["age"]
    tol2 = lf2.TextItem
    tol2.contents = d

    lf3 = doc.ArtLayers["gender"]
    tol3 = lf3.TextItem
    tol3.contents = f

    lf4 = doc.ArtLayers["pid"]
    tol4 = lf4.TextItem
    tol4.contents = c

    lf4 = doc.ArtLayers["date"]
    tol4 = lf4.TextItem
    tol4.contents = e

    lf5 = doc.ArtLayers["contact"]
    tol5 = lf5.TextItem
    tol5.contents = g

    lf6 = doc.ArtLayers["complaint"]
    tol6 = lf6.TextItem
    varH="                       "+h.rstrip("\n")
    tol6.contents =varH

    lf7 = doc.ArtLayers["allergy"]
    tol7 = lf7.TextItem
    tol7.contents = i.rstrip("\n")

    lf8 = doc.ArtLayers["history"]
    tol8 = lf8.TextItem
    varJ="                                              "+j.rstrip("\n")
    tol8.contents =varJ

    lf9 = doc.ArtLayers["R"]
    tol9 = lf9.TextItem
    tol9.contents = k.rstrip("\n")
    options = win32com.client.dispatch('Photoshop.ExportOptionsSaveForWeb')
    options.Format = 13
    options.PNG8 = False
    pngfile =ExpDir+f"/{c}-{b}_({e}).png"
    doc.Export(ExportIn=pngfile,ExportAs=2,Options=options)
    messageBox.showinfo("Prescription Generator","Prescription has been saved in the desired location successfully!")

解决方法

换行符有3种表示方式:

  • MacOS 使用 \r
  • Linux 使用 \n
  • Windows 使用 \r\n

Python 和 tkinter 使用 \n,但看起来 psApp.Application 使用 \r。这就是文档未正确呈现的原因。有关详细信息,请阅读 this 问题的答案。