PysimpleGUI combo source from dataFrame - python

please advise my project to the attched picture(error&problem)
1.combo source==>one of column in dataframe: need to fix, please help me
2.last record No(ExNo) in excel ==>should to reflect on the input screen as ExNo
3.int(['Total'])-int(['VAT']) ==>error
import PySimpleGUI as sg
from datetime import datetime
import pandas as pd
# Add some color to the window
sg.theme('DarkTeal9')
coa_file = 'D:\92Python\Acdb\coa.xlsx'
coa_data = pd.read_excel(coa_file, sheet_name="coa", skiprows = 1, index_col=False)
coa_df = pd.DataFrame(coa_data) #.reset_index(drop=True, inplace=True)
coa_df1 =coa_df.iloc[:,[0,1]] <--error
ExNo = 1
#print(coa_df1)
EXCEL_FILE = 'D:\92Python\Acdb\Data_Entry.xlsx'
df = pd.read_excel(EXCEL_FILE)
layout = [
[sg.Text('Please fill out the following fields:')],
[sg.Text('Expense No', size=(15,1), justification= 'left', key='ExNo')], <--error
[sg.Text('Date', size=(15,1)), sg.InputText(key='Date'), sg.CalendarButton("Date", close_when_date_chosen=True, target="Date", location=(0,0), no_titlebar=False)],
[sg.Text('COA', size=(15,1)), sg.InputCombo(coa_df1, key='COA',size=(50,1))],
[sg.Text('Supplier', size=(15,1)), sg.InputText(key='Supplier')],
[sg.Text('Total', size=(15,1)), sg.InputText(key='Total')],
[sg.Text('VAT', size=(15,1)), sg.InputText(key='VAT')],
#[sg.Text('Amount', size=(15,1), justification= 'left', key='Amount')],
[sg.Text('Paid', size=(15,1)),
sg.Checkbox('Cash', key='Cash'),
sg.Checkbox('CreditCard', key='CreditCard'),
sg.Checkbox('Bank', key='Bank'),
sg.Checkbox('Owners', key='Owners')],
[sg.Text('Description', size=(15,1)), sg.InputText(key='Desc')],
[sg.Text('No. of Children', size=(15,1)), sg.Spin([i for i in range(0,16)],
initial_value=0, key='Children')],
[sg.Submit(), sg.Button('Clear'), sg.Exit()]
]
window = sg.Window('Simple data entry form', layout, no_titlebar=False, location=(10,10), size=(800,600), keep_on_top=True)
#window['Date'].bind("<Return>", "_Enter")
def clear_input():
for key in values:
window[key]('')
return None
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Exit':
break
if event == 'Clear':
clear_input()
if event == 'Submit':
#amount = float(int(['Total'])-int(['VAT']))
#window['Amount'].Update(amount)
new_record = pd.DataFrame(values, index=[0])
df = pd.concat([df, new_record], ignore_index=True)
df.to_excel(EXCEL_FILE, index=False)
sg.popup('Data saved!')
clear_input()
window.close()

Related

Entry form and visualize with PySimpleGUI in 2 different sheets

I'm trying to export in an existing file a row of datas in sheet1 every time a person complete the form but I also have a button to visualize some cells in sheet2. Every time I try to entry information the file got corrupted and tries to save the most data and no info is exported. Maybe I need to active 2 sheets at different times?
EXCEL_FILE = 'example.xlsx'
df = pd.read_excel(EXCEL_FILE)
workbook = load_workbook(filename='example.xlsx')
workbook.sheetnames
workbook.active = workbook['sheet2']
sheet = workbook.active
layout = [
[sg.Text('Por favor rellenar los siguientes campos:')],
[sg.Text('Fecha de Inicio', size=(15,1)), sg.InputText(key='Fecha de Inicio')],
[sg.Text('Hora de Inicio', size=(15,1)), sg.InputText(key='Hora de Inicio')]]
def clear_input():
for key in values:
window[key]('')
return None
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Salir':
break
if event == 'Limpiar':
clear_input()
if event == 'Confirmar':
wb = load_workbook('example.xlsx')
df = df.append(values, ignore_index=True)
df.to_excel('example.xlsx', index=False)
wb.save('example.xlsx')
sg.popup('Informe enviado!')
clear_input()
if event == 'Visualizar':
for value in sheet.iter_rows(min_row=1,
max_row=20,
min_col=1,
max_col=3,
values_only=True):
sg.Print(value)
window.close()

Is there a way to clear a tree element in PySimpleGUI before adding new data?

I have a window with a tree element that shows files and folders when I enter a path. I need this tree to clear if I enter a new path. At the moment the tree appends the files/folders from each path I enter. Is there a way to refresh the tree element before entering new information into it?
My code is similar to this:
import PySimpleGUI as sg
import os
starting_path = os.getcwd()
treedata = sg.TreeData()
folder_icon = b'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIW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B7Z00G3xVc2wZeMSI4S7sVYkSk5Z/4PyBWROqvox3A28PN2cjUwinQC9QyckKALxj4kv2auK0xAAAAAElFTkSuQmCC'
def add_files_in_folder(parent, dirname):
files = os.listdir(dirname)
for f in files:
fullname = os.path.join(dirname, f)
if os.path.isdir(fullname): # if it's a folder, add folder and recurse
treedata.Insert(parent, fullname, f, values=[], icon=folder_icon)
add_files_in_folder(fullname, fullname)
else:
treedata.Insert(parent, fullname, f, values=[os.stat(fullname).st_size], icon=file_icon)
def main_window():
column_one = sg.Column([
[sg.Tree(data=treedata,
headings=['Size', ],
auto_size_columns=True,
select_mode=sg.TABLE_SELECT_MODE_EXTENDED,
num_rows=20,
col0_width=40,
key='-TREE-',
show_expanded=False,
enable_events=True,
expand_x=True,
expand_y=True,
), ],
[sg.B('Open', k='-OPEN-'), sg.B('Add', k='-ADD-')],
])
layout = [
[sg.T('Some text')],
[sg.HorizontalSeparator()],
[sg.T('Select the files / folders')],
[column_one],
[sg.B('Cancel', k='-EXIT-')]
]
return sg.Window('some window', layout, resizable=True, finalize=True)
window = main_window()
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, '-EXIT-'):
break
print(event, values)
if event == '-OPEN-':
starting_path = sg.popup_get_folder('Folder to display')
add_files_in_folder('', starting_path)
window['-TREE-'].update(values=treedata)
window.close()
Any help is appreciated!
Following code demo how to create/clear/append data to treedata for Table element. Here all item added as children of root ''.
import PySimpleGUI as sg
def add_data(treedata, offset):
default = [[str((i+1)*(j+offset+1)) for i in range(9)] for j in range(9)]
for i, value in enumerate(default):
treedata.insert('', i+offset+1, i+offset+1, value)
return treedata
treedata = sg.TreeData()
treedata = add_data(treedata, 0)
index = 10
layout = [
[sg.Tree(
data=treedata,
headings=[str(i+1) for i in range(9)],
col0_heading='9x9',
col0_width=5,
num_rows=20,
key='-TREE-',
)],
[sg.Button('Clear'), sg.Button('Reset'), sg.Button('Append')],
]
window = sg.Window('Title', layout, finalize=True)
tree = window['-TREE-']
tree.Widget.column('#0', anchor='e')
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event == 'Clear':
treedata = sg.TreeData()
tree.update(values=treedata)
index = 0
elif event == 'Reset':
treedata = add_data(sg.TreeData(), 0)
tree.update(values=treedata)
index = 10
elif event == 'Append':
treedata = add_data(treedata, index)
tree.update(values=treedata)
index += 10
window.close()

PysimpleGui window gets rescaled to smaller size when i recall the function in which pysimpleGUI is present

I am creating an app in which i want display data in tabular format i created a GUI windows that displays the data properly but whenever i recall the same function or any other GUI function my GUI window Gets Resized/Rescaled to a smaller size
def tableGUIP(file):
data = []
header_list = []
df = pd.read_csv(file, sep=',', engine='python', header=None)
data = df.values.tolist() # read everything else into a list of rows
header_list = df.iloc[0].tolist()
data = df[1:].values.tolist()
layout = [
[sg.Table(values=data,
headings=header_list,
display_row_numbers=False,
auto_size_columns=True,
row_height=20,
num_rows=min(20, len(data)))],
[sg.Text('Column', size =(15, 1))],
[sg.Button("Rank"),sg.Button("Live"),sg.Button("2020"),sg.Button("Area"),sg.Button("Density"),sg.Button("Growth"),sg.Button("World %"),sg.Exit()]
]
window = sg.Window('Table', layout, grab_anywhere=False,use_default_focus=True,keep_on_top=True,finalize=True)
event, values = window.read()
while True:
if event in (None, 'Exit'):
sortcol('Exit')
break
# in ('Rank','2022 (Live)', '2020 Population', 'Area', 'Density', 'Growth Rate', 'World %'):
if event == "Rank":
sortcol('Rank')
break
elif event=="Live":
sortcol('2022 (Live)')
break
elif event=="2020":
sortcol('2020 Population')
break
elif event=="Area":
sortcol('Area')
break
elif event=="Density":
sortcol('Density')
break
elif event=="Growth":
sortcol('Growth Rate')
break
elif event=="World %":
sortcol('World %')
break
window.close()
This is the GUI windows after the first occurrence occurs
This is the GUI windows When the first occurrence occurs

how to pysimplegui manage dataframe in excel?

i want to delete dataframe unnamed in red arrow , and the i want to add some text when i click submit i have index from 1 not in 0 like this
Data_entry.xlsx
can you give me solution about this problem ?
in above my code in python 3
import PySimpleGUI as sg
import pandas as pd
# importing openpyxl module
import openpyxl
# Give the location of the file
path = "C:\\Users\\Admin\\Desktop\\WEB\\PYTHON_PYSIMPLEGUI\\Data_Entry.xlsx"
sg.theme('DarkGreen7')
EXCEL_FILE = 'Data_Entry.xlsx'
df = pd.read_excel(EXCEL_FILE)
my_img = sg.Image(r'C:\Users\master\Desktop\WEB\PYTHON_PYSIMPLEGUI\logo.png')
"""
# Template Taskbar
menu_def = [['File', ['Open', 'Save', 'Exit',]],
['Edit', ['Paste', ['Special', 'Normal',], 'Undo'],],
['Help', 'About...'],]
"""
menu_def = [['File', ['Exit']],['Help', 'About...'],]
layout = [
[sg.Menu(menu_def)],
[sg.Column([[my_img]], justification='center')],
[sg.Text('Simacan ( SIstem Monitoring And Controling Absen Nilai')],
[sg.Text('Nama', size=(15,1)), sg.InputText(key='Nama')],
[sg.Text('Kehadiran', size=(15,1)), sg.Combo(['Hadir', 'Sakit', 'Tidak Masuk'], key='Keterangan')],
[sg.Submit(), sg.Exit()]
]
window =sg.Window('Aplikasi Simacan versi 1.2', layout,size=(800, 600), font='Courier 12')
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Exit':
break
if event == 'Submit':
df = df.append(values, ignore_index=True)
df.to_excel(EXCEL_FILE, index=True)
sg.popup('Data saved !')
print(event, values)
window.close()
There's are some issues here.
Create a blank excel file to store your data.
Open excel file as a dataframe, option index_col set the index column or you may get Unnamed: 0 column as index in your dataframe.
df = pd.read_excel(EXCEL_FILE, index_col=[0])
There's one extra item 0 in dictionary values, it is the key of sg.Menu, should remove it before you append the values to your dataframe by
del values[0]
You can re-index your dataframe by
df.index = np.arange(1, len(df)+1)
You can save dataframe to your excel file only before end of you script, of course, write each new record to your excel file is still fine.

cannot build table with PySimpleGUI

I would like for tab 2 to show a table of all existing reservations.
I have tried making the dataframe a string and then a list.
import pandas as pd
from pandas import DataFrame
#create dataframe to simulate databse with names and dates
data = {'Name': ['Joe Smith', 'Jason Leary','Bill Murray'],
'Start Date': ['2019/10/01', '2019/11/01','2019/12/01'],
'End Date': ['2019/10/15', '2019/11/15','2019/12/15']
}
df = pd.DataFrame (data, columns = ['Name','Start Date','End Date'])
Data_Table = df.to_string()
# Stuff inside window
tab1_layout = [
[sg.Text('The Scheduler')],
[sg.Combo(name, size=(30,4), enable_events=True)],
[sg.Combo(reason, size=(30,4), enable_events=True)],
[sg.T('Start Date')],
[sg.In('', size=(10,1), key='input1')],
[sg.CalendarButton('Choose Start Date', target='input1', key='date1',format='%Y/%m/%d')],
[sg.T('End Date')],
[sg.In('', size=(10,1), key='input2')],
[sg.CalendarButton('Choose End Date', target='input2', key='date2', format='%Y/%m/%d')],
[sg.Button('Submit')]]
# create a table to show names and dates with an export to CSV button
tab2_layout = [[sg.Table(values=Data_Table, max_col_width=25, background_color='lightblue',
auto_size_columns=True, justification='right', alternating_row_color='blue', key='_table_')],
[sg.Button('Update')]]
tab3_layout = [[sg.T('This is inside tab 3')],
[sg.In(key='_in3_')]]
# create the window
layout = [[sg.TabGroup([[sg.Tab('Scheduler', tab1_layout, key='_mykey_'),
sg.Tab('Schedule', tab2_layout),
sg.Tab('Admin', tab3_layout)]],
key='_group2_', title_color='darkgrey',
selected_title_color='black', tab_location='topleft')]]
window = sg.Window('My window with tabs', default_element_size=(30,1)).Layout(layout)
# event loop to process events and get the values of inputs
while True:
event, values = window.Read()
print(event, values)
if event in (None, 'Exit'):
break
if event == 'Update':
window.FindElement('_table_').Update( row_colors=((8,'white', 'red'), (9,'black')))
window.Close()
I would like for a table to show on tab 2 with existing reservations. Ultimately this will come from a db but for now I have created a pd.DataFrame.
The error is
TclError: Invalid column index
But I have tried strings and lists.
In sg.table you need to include:
headings = header_list
header_list = [str(x) for x in range(len(data[0]))]
tab2_layout = [[sg.Table(values=Data_Table, max_col_width=25,
background_color='lightblue',
auto_size_columns=True,
justification='right',alternating_row_color='blue',
key='_table_', headings = header_list)]
[sg.Button('Update')]]
For more Details See:
https://repl.it/#PySimpleGUI/Table-Element

Categories