Home > front end >  How do you output text to an Editor (for prining) in PySimpleGUI?
How do you output text to an Editor (for prining) in PySimpleGUI?

Time:02-14

I have written a program using Tkinter and then, the same program using PySimpleGUI. When I run a report in the Tk program in outputs the data to the console and also opens an editor and lists the formatted data so that it can be printed. The PySimpleGUI program also outputs the data to the console and opens the editor but does not populate it. Can anyone see what the 'problem/solution' may be? I have only shown the code related to the report writer for brevity. I suspect that the problem lies in the last approximately 6 lines.

Secondly, if I use a popup_get_date() it produces a date in the wrong format (I want 'yyyy-MM-dd'. Is there a way to tell the popup to produce the date in the correct format? For example I want the following to happen: window['ELEMENT].update(sg.popup_get_date()) to put a formatted date into the Element. Thank you in advance.

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()

CodePudding user response:

Why not print directly?

In one of my programs that has to work both on POSIX systems and ms-windows, I have the following:

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.")

So now _printfile is specific to the operating system it is running on. It can be used to print the content that has been written to a (temporary) file.

  • Related