如何在 PySimpleGUI 中将文本输出到编辑器(用于打印)?

How do you output text to an Editor (for prining) in PySimpleGUI?

我使用 Tkinter 编写了一个程序,然后使用 PySimpleGUI 编写了相同的程序。当我 运行 Tk 程序中的报告将数据输出到控制台时,还会打开一个编辑器并列出格式化数据以便打印。 PySimpleGUI 程序还将数据输出到控制台并打开编辑器但不填充它。谁能看出 'problem/solution' 可能是什么?为了简洁起见,我只展示了与报告编写器相关的代码。我怀疑问题出在最后大约 6 行。

其次,如果我使用 popup_get_date() 它会生成错误格式的日期(我想要 'yyyy-MM-dd'。有没有办法告诉弹出窗口以正确的格式生成日期?例如,我希望发生以下情况:window['ELEMENT].update(sg.popup_get_date()) 将格式化日期放入元素中。

import PySimpleGUI as sg
import tkinter as tk
from tkinter import ttk
from tkcalendar import Calendar, DateEntry
import sqlite3
import datetime as dt
import time
from prettytable import PrettyTable
import subprocess, sys
from tkinter.filedialog import askopenfilename

def income_by_cat_report():

    income_by_cat_layout=[

        [sg.Push(),sg.T('Income by category and date',font=40, text_color='blue'),sg.Push()],
        [sg.T('Select the category'),sg.Combo(I_Analyse_data,size=(15,1),key='-INCAT-',enable_events=True,tooltip='Please select a category from the dropdown box')],
        [sg.T('Select a Start date:'),sg.CalendarButton('Calendar',  target='-STARTDT-', key='_STDATE_',format='%Y-%m-%d'),sg.In(key='-STARTDT-',size=10)],
        [sg.T('Select an End date:'),sg.CalendarButton('Calendar',  target='-ENDDT-', key='_ENDATE_',format='%Y-%m-%d'),sg.In(key='-ENDDT-',size=10)],
        [sg.Button('Quit',size=8,button_color='red'),sg.Push(),sg.Button('Run',size=8,button_color='green',key='-RUN-')]

    ]

    income_by_cat_report=sg.Window('Income by category Report',income_by_cat_layout,modal=True)

    while True:

        event,values=income_by_cat_report.read()
        if event in (None, 'Quit'):
            break
        elif event == '-RUN-':

            import subprocess
            total = 0
            proc=subprocess.Popen(['/usr/bin/idle-python3.9',"FSCashBook.txt"])

            c_Category=values['-INCAT-']
            s_Date=values['-STARTDT-']
            e_Date=values['-ENDDT-']
            

            print('The category selected is ' + c_Category)
            print('The start date is: ' + s_Date)
            print('The end date is: ' + e_Date)


            Sql=("SELECT tDate as Report_Date, tAnalysis as Category,tDesc as Description,Details as Details, printf('%,.2f',fAmnt) as Spend FROM FSCashBook WHERE tAnalysis = ?" +
                "AND tDate >= ?  AND tDate <= ? order by ID Asc ")
                 
            Sql1=("SELECT tAnalysis, SUM(fAmnt) as TotalSpend FROM FSCashBook WHERE tAnalysis = ?"
                      "AND tDate >= ?  AND tDate <= ? order  by Id Desc LIMIT 1")
            

            conn = sqlite3.connect(r'/home/bushbug/Databases/FSCashBook')
            curs = conn.cursor()
            curs1=conn.cursor()
            curs2=conn.cursor()
            
            curs.execute(Sql,(c_Category,s_Date,e_Date))
            curs1.execute(Sql1,(c_Category,s_Date,e_Date))
            col_names = [cn[0] for cn in curs.description]
            rows = curs.fetchall()

            try:

                print(rows[0])

            except IndexError:

                sg.popup('No data to process!','There is no data to retrieve for the report. Please check your dates!')

                break

            """Category below is the analysis group eg. Surgery, Toenail, Ffingernails etc"""

            x = PrettyTable(col_names,left_padding_width=0)
            x.title='Data for ' +c_Category+', date range from '+s_Date +' to '+e_Date
            #x.set_style=(MSWORD_FRIENDLY)
            x._max_width = {"Date":10, "Category":15, "Description":15, "Procedure":20,"Fee Income" :10}
            x.field_names=["Date","Category ","Patient","Procdure","Income Amount"]
            # x.align = "r"
            # x.align[col_names[0]] = "l"
            x.align['Date'] = 'l'
            x.align['Category']='l'
            x.align['Description']='l'
            x.align['Details']='l'
            x.align['Spend Amount']='r'
            
            x.padding_width = 1
            
            for row in rows:
                
                x.add_row(row)

            result=curs1.execute(Sql1,(c_Category,s_Date,e_Date))
                        
            for row in result:

                TotalSpend=float(row[1])
                
                x.add_row(["","","","",""])
                x.add_row(["==========","=======","=========","==========","=========="])
                  
                x.add_row(["TOTALS","","", "",str(round(float(TotalSpend),2))])
                
            tabstring = x.get_string()

            output=open("IncomeReports.txt","w")
            output.write(tabstring)
            print(tabstring)
            output.close()
            conn.close()

    income_by_cat_report.close()

为什么不直接打印?

我的一个程序必须同时在 POSIX 系统和 ms-windows 上运行,我有以下内容:

if __name__ == "__main__":
    # Platform specific set-up
    if os.name == "nt":
        from win32api import ShellExecute

        home = os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"]

        def _printfile(fn):
            """Print the given file using the default printer."""
            rv = ShellExecute(0, "print", fn, None, home, 0)
            if 0 < rv <= 32:
                messagebox.showerror("Printing failed", f"Error code: {rv}")

    elif os.name == "posix":
        from subprocess import run

        def _printfile(fn):
            """Print the given file using “lpr”."""
            cp = run(["lpr", fn])
            if cp.returncode != 0:
                messagebox.showerror("Printing failed", f"Error code: {cp.returncode}")

    else:

        def _printfile(fn):
            """Report that printing is not supported."""
            messagebox.showinfo("Printing", "Printing is not supported on this OS.")

所以现在 _printfile 特定于它 运行 所在的操作系统。它可用于打印已写入(临时)文件的内容。