Entry form and visualize with PySimpleGUI in 2 different sheets - python

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

Related

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

PysimpleGUI combo source from dataFrame

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

How to make my for loop work in openpyxl?

Hi I am in process of writing a python code to input search and edit data into excel.
my chosen format for the UI is PySimpleGUI and my xlsx package is openpyxl.
I have been coding for approximately 3 weeks.
I probably bit off more than I can chew but I won't give up.
I need to know why my for loop won't work so I can fix it.
here is the offending code:
import PySimpleGUI as sg
import pandas as pd
import openpyxl as op
def weekly_wage():
filename = 'Payroll.xlsx'
wb = op.load_workbook(filename, data_only=True)
ws = wb.worksheets[0]
ws_tables = []
layout = [
[sg.Text('Employee Name', size=(15,1), font=('ariel', 16)), sg.InputText(key='-Name-', font=('ariel',16))],
[sg.Text('Week Ending', size=(15,1), font=('ariel',16)), sg.InputText(key='-Date-', font=('ariel',16))],
[sg.Submit(font=('ariel', 16))],
[sg.Text('The Weekly Wage is:', font=('ariel', 16))],
[sg.Output(size=(10, 1))]
]
window = sg.Window('Gross Wages Search', layout, size=(450,250))
# Event Loop
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
if event == 'Submit':
if event == 'Submit':
key1 = window['-Name-'] # this gives a callable object to the Input keys
key2 = window['-Date-']
rows = ws.iter_rows()
name = []
date = []
gross = []
for a,b,aw in rows:
name.append(a)
date.append(b)
gross.append(aw)
if a.value == key1 and b.value == key2:
print (aw.value)
break
else:
print('Try Again')
break
window.close()
weekly_wage()
I have poored over the openpyxl docs for hours per night, and I have performed that many google searches I now have shares!!

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.

Hitting Error while iterating the row under While loop followed by If Else condition for Pandas Dataframe

With my current task I am trying to iterate all of my excel rows and then copy each row as a new record to the destination template file. the source file and the destination files are different hence I am assigning the value to the destination cell.
# code run sample file
# import os
import pandas as pd
import xlwings as xw
newdir_path = " "
file1 = "list.xlsx"
# read the source file
data = pd.read_excel(file1, sheet_name=0, header=0,
index_col=False, keep_default_na=True)
# creating pandas dataframe from the source file
df = pd.DataFrame(data, columns=['Funktion', 'AD65', 'W70', 'B14', 'AC21'])
B14 = ['RR', 'BB', 'RA', 'MM']
booleans = []
# to iterate all the rows
for i in df.itertuples(index=True):
# only to read the rows where column AD65(2nd column) does not have blank value or none
while i[AD65] != 'None':
# to retrieve the row values
# when B14 value is RR
if B14 == 'RR':
print(i)
# retrieving the values
Funktion = i.Funktion
AD65 = i.AD65
W70 = i.W70
B14 = i.B14
AC21 = i.AC21
booleans.append(True)
# when B14 is B1
elif B14 == 'BB':
print(i)
Funktion = i.Funktion
AD65 = i.AD65
W70 = i.W70
B14 = i.B14
AC21 = i.AC21
booleans.append(True)
elif B14 == 'RA':
# repeating the same as above
booleans.append(True)
elif B14 == 'MM':
booleans.append(True)
else:
# I want to skip the rows when B14 value is blank
Note: I also tried my condition with if df.loc[['B14'] == 'RR']: and it is throwing raise KeyError(key)
KeyError: False

Categories