convert path to excel using python and pysimplegui gives typeError

Question:

I am trying to write a script which writes path data to an excel file. The function is working, I just want to create an simple GUI using PySimpleGUI where the user can give a path. The path variable is used in the function. Now I have the error:

str_path = int(values['-INF1-'])
TypeError: tuple indices must be integers or slices, not str

This is my code:

import PySimpleGUI as sg
import ctypes
import platform
import os
import pandas as pd
from pathlib import Path
from docxtpl import DocxTemplate

def make_dpi_aware():
    if int(platform.release()) >= 8:
        ctypes.windll.shcore.SetProcessDpiAwareness(True)

make_dpi_aware()

sg.LOOK_AND_FEEL_TABLE['MyCreatedTheme'] = {'BACKGROUND': '#DCD7C9',
                                        'TEXT': '#000000',
                                        'INPUT': '#E9DAC1',
                                        'TEXT_INPUT': '#000000',
                                        'SCROLL': '#99CC99',
                                        'BUTTON': ('#000000', '#54BAB9'),
                                        'PROGRESS': ('#D1826B', '#CC8019'),
                                        'BORDER': 1, 'SLIDER_DEPTH': 0, 
                                        'PROGRESS_DEPTH': 0, }

sg.theme('MyCreatedTheme')

layout = [
       [sg.T('Voer een pad in: '), sg.Input(key='-INF1-')],
       [sg.FolderBrowse('Opslaan in', key="-IN-")],
       [sg.Button("Open excel bestand"), sg.Exit()]
]

window = sg.Window('Pad naar excel generator', layout, element_justification="right", modal=True, font='Any 12')

values = window.read()
str_path = int(values['-INF1-'])
path = Path(str_path)

def list_files(path):
    files = []
    for r, d, f in os.walk(path):
        for file in f:
            files.append(os.path.join(r, file))
    df = pd.DataFrame(files, columns = ['path'])
    df['filename'] = df['path'].str.split('\').str[-1]
    df['path'] = df['path'].str.replace(r'\[^\]*$', '')
    df.to_excel('files.xlsx', index = False)
    return df

list_files(path)

while True:
        event = window.read()
        if event == sg.WIN_CLOSED or event == "Exit":
            break
        if event == "Open excel bestand":
            list_files(values['-INF1-'])
            output_path = Path(values["-IN-"]) / f"filestopath.docx"
            doc = DocxTemplate(output_path)
            doc.save(output_path)
            os.startfile(output_path)

window.close()

Can someone explain to me what is going wrong? Any help would be appreciated!

Asked By: Bosbes

||

Answers:

This is how PySimpleGUI docs tell us to read event and values from Window:

event, values = window.read()

Instead you do (in different places):

values = window.read()
...
event = window.read()

In your code values/event is assigned a tuple of (<EVENT>, <VALUES>), which you try to process as if it were PySimpleGUI object.

If you need only one part of the tuple, do this instead:

_, values = window.read()
...
event, _ = window.read()
Answered By: Klas Š.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.