I'm creating a simple calculation program using tkinter module and want to convert to exe as I want it to be executable at any pc. But somehow the error message show (failed to execute script pyi_rth_win32comgenpy).
I've try used pyinstaller ( cmd and the one on GitHub at : https://github.com/brentvollebregt/auto-py-to-exe) but to no avail. I also try using both types of python file (.py and .pyw)
from tkinter import *
from tkinter.filedialog import askopenfilename
import pandas as pd
from tkinter import messagebox
from pandastable import Table, TableModel
class Window(Frame):
def __init__(self, master =None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title('GUI')
self.pack(fill=BOTH, expand=1)
quitButton = Button(self, text='quit', command=self.client_exit)
quitButton.place(x=0, y=230)
# fileButton = Button(self, text='Browse Data Set', command=self.import_data)
# fileButton.place(x=150, y=0)
fileButton = Button(self, text='SBO', command=self.sbo)
fileButton.place(x=200, y=50)
fileButton = Button(self, text='CBO', command=self.cbo)
fileButton.place(x=150, y=50)
# menu = Menu(self.master)
# self.master.config(menu=menu)
#
# file = Menu(menu)
# file.add_command(label='Save',command=self.client_exit)
# file.add_command(label='Exit', command= self.client_exit)
# menu.add_cascade(label='File', menu=file)
#
# edit = Menu(menu)
# edit.add_command(label='Undo')
# menu.add_cascade(label='Edit', menu=edit)
def client_exit(self):
exit()
# def import_data(self):
#
# csv_file_path = askopenfilename()
# # print(csv_file_path)
# df = pd.read_excel(csv_file_path)
# return df
def sbo(self):
csv_file_path = askopenfilename()
df = pd.read_excel(csv_file_path)
data = df.drop(df.index[0]) # remove first row
data['BOVal%'] = data['BOVal%'].astype(str) # convert to string
data['BOQty%'] = data['BOQty%'].astype(str)
data['CustomerPONo'] = data['CustomerPONo'].astype(str)
data['OrdNo'] = data['OrdNo'].astype(str)
data['VendorNo'] = data['VendorNo'].astype(str)
pivot = data.pivot_table(index='Style', aggfunc='sum') # first pivot
pivoted = pd.DataFrame(pivot.to_records()) # flattened
pivoted = pivoted.sort_values(by=['BOVal'], ascending=False) # sort largest to smallest
pivoted['Ranking'] = range(1, len(pivoted) + 1) # Ranking
cols = pivoted.columns.tolist()
cols = cols[-1:] + cols[:-1]
pivoted = pivoted[cols]
pivoted = pivoted.set_index('Ranking')
col = df.columns.tolist()
col = (col[22:23] + col[15:17] + col[:14] + col[17:22] + col[23:37]) # rearrange column
data = df[col]
data = data.sort_values(by=['BOVal'], ascending=False) # sort value
data['Ranking'] = range(1, len(data) + 1) # Set rank
colm = data.columns.tolist()
colm = colm[-1:] + colm[:-1] # rearrange rank column
data = data[colm]
data = data.set_index('Ranking')
# sumboval = data['BOVal'].sum()
# sumboqty = data['BOQty'].sum()
# rounded = sumboval.round()
dates = data['SnapShotDate']
# print(dates)
dates = dates.iloc[1].strftime('%d%m%Y')
sos = data['SOS']
sos = sos[2]
result = pivoted.iloc[:10, :3]
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('%s SBO %s .xlsx' % (sos, dates), engine='xlsxwriter')
# Write each dataframe to a different worksheet.
result.to_excel(writer, sheet_name='pivot')
df.to_excel(writer, sheet_name=dates)
data.to_excel(writer, sheet_name='SBO')
# Close the Pandas Excel writer and output the Excel file.
writer.save()
messagebox.showinfo("Note", "Calculation Completed")
def cbo(self):
csv_file_path = askopenfilename()
Stylemat = askopenfilename()
df = pd.read_excel(csv_file_path)
sm = pd.read_excel(Stylemat)
df = df.drop(df.index[0])
df.insert(loc=8, column='PH', value=['' for i in range(df.shape[0])])
df.insert(loc=9, column='Site', value=['' for i in range(df.shape[0])])
df['Region'] = df['Region'].fillna('"NA"')
df['S&OP Style Aggrt'] = df['S&OP Style Aggrt'].astype(str)
sm['Style'] = sm['Style'].astype(str)
dates = df['Date_Rp']
# print(dates)
dates = dates.iloc[1]
w = list(dates)
w[1] = '-'
w[3] = '-'
temp = w[0]
w[0] = w[2]
w[2] = temp
dates = "".join(w)
rowcount = len(df)
rowstyle = len(sm)
i = 0
j = 0
Style = []
for i in range(rowcount):
for j in range(rowstyle):
if df.iloc[i, 7] == sm.iloc[j, 0]:
df.iloc[i, 8] = 'Horizon'
df.iloc[i, 9] = sm.iloc[j, 2]
table = pd.pivot_table(df[df.PH == 'Horizon'], index='S&OP Style Aggrt', columns='Region',
values='Net CBO Value', aggfunc='sum')
table['Grand Total'] = table.sum(axis=1)
table = table.sort_values(by=['Grand Total'], ascending=False)
table['Ranking'] = range(1, len(table) + 1)
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('CBO %s .xlsx' % dates, engine='xlsxwriter')
# Write each dataframe to a different worksheet.
table.to_excel(writer, sheet_name='pivot')
df.to_excel(writer, sheet_name=dates)
sm.to_excel(writer, sheet_name='StyleMat')
# Close the Pandas Excel writer and output the Excel file.
writer.save()
messagebox.showinfo("Note", "Calculation Completed")
root = Tk()
root.geometry('400x300')
app = Window(root)
root.mainloop()
I'd like to know how to find the main reason for this error and where to look for it, is it either my scripting method is incorrect or is there any additional file or module that I need. Appreciate in advance for your help. Thank you
I uninstalled everything related to win32 (pypiwin32, pywin32, pywin32-ctypes, pywinpty) and then installed again and magically it worked.
Took the idea from here and here.
this is quite late, but the answer to that issue is just the py to exe cannot execute on numpy 1.17. after downgrade to numpy 1.16, the program can run normally.
You are getting this error failed to execute script pyi_rth_win32comgenpy as result of not including the images you used for you icons and labels
I included images of icon, Question mark and the title
copy this images and include it the directory you have your pyi_rth_win32comgenpy executable.
Related
I'm having a little trouble with openpyxl. I'm updating an excel with historic data something like this:
The excel has 2 sheets with this data, both are almost the same. The thing is that after I add the new rows and aply the formats, in the second sheet for some reason a lot of row are hidden, like this:
This is my code:
from copy import copy
import pandas as pd
from openpyxl import load_workbook
datos = pd.Dataframe(my_data) # This is not right but I already have the data in a DF
today = datos[col1].loc[0].strftime("%Y-%m-%d")
tomorrow = datos[col1].loc[1].strftime("%Y-%m-%d")
historic = 'my_excel.xlsx'
logger.info('Reading Excel')
wb = load_workbook(historic)
sheets = wb.sheetnames
for sheet in sheets:
logger.warning(f'************* {sheet} *************')
ws = wb[sheet]
logger.info(f'active: {wb.active}')
logger.info(f"len D: {len(ws['D'])}")
logger.info(f"len E: {len(ws['E'])}")
max_row = len(ws['D'])
logger.info('Last D cell')
last_D_cell = ws.cell(row=max_row, column=4)
last_D_cell_value = last_D_cell.value.strftime("%d/%m/%Y")
logger.info('New Cell')
new_D_cell = ws.cell(row=max_row + 1, column=4)
new_D_cell.font = copy(last_D_cell.font)
new_D_cell.border = copy(last_D_cell.border)
new_D_cell.number_format = copy(last_D_cell.number_format)
new_D_cell.alignment = copy(last_D_cell.alignment)
new_D_cell.fill = copy(last_D_cell.fill)
new_D_cell.value = datos[col1].loc[1].strftime("%d/%m/%Y")
logger.info('Penultimate D Cell')
penultimate_D_cell = ws.cell(row=max_row - 1, column=4)
last_D_cell.font = copy(penultimate_D_cell.font)
last_D_cell.border = copy(penultimate_D_cell.border)
last_D_cell.number_format = copy(penultimate_D_cell.number_format)
last_D_cell.alignment = copy(penultimate_D_cell.alignment)
last_D_cell.fill = copy(penultimate_D_cell.fill)
logger.info('Last E Cell')
last_E_cell = ws[f'E{max_row}']
new_E_cell = ws.cell(row=max_row + 1, column=5)
new_E_cell.font = copy(last_E_cell.font)
new_E_cell.border = copy(last_E_cell.border)
new_E_cell.number_format = copy(last_E_cell.number_format)
new_E_cell.alignment = copy(last_E_cell.alignment)
new_E_cell.fill = copy(last_E_cell.fill)
new_E_cell.value = tomorrow_value
logger.info('Penultimate E')
penultimate_E_cell = ws[f'E{max_row - 1}']
last_E_cell.font = copy(penultimate_E_cell.font)
last_E_cell.border = copy(penultimate_E_cell.border)
last_E_cell.number_format = copy(penultimate_E_cell.number_format)
last_E_cell.alignment = copy(penultimate_E_cell.alignment)
last_E_cell.fill = copy(penultimate_E_cell.fill)
logger.info('SAving Excel')
wb.save(historic)
With this code, the last sheet it works will have the hidden rows, and I don't know why is this happening.
Hope someone can help me thanks
EDIT: I'm on Ubuntu 20.4 LTS, and the resulting files has been opened in both Ubuntu and Windows 10 and the same situation appears.
I am trying to add a new row to an AgGrid Table using streamlit and python
At this point, I just want to add 1 or more new rows to the table generated by the AgGrid by pressing the "add row" button.
After pressing the "add row" button I generate a second table with the new row mistakenly, so I get 2 data-tables instead of updating the main table.
The initial data df = get_data() is been gathered from a SQL query. I want to add a new row and (for now) save it into a CSV file or at least get the updated DF with the new row added as an output and graph it
My current code
import streamlit as st
from metrics.get_metrics import get_data
from metrics.config import PATH_SAMPLES
filename: str = 'updated_sample.csv'
save_path = PATH_SAMPLES.joinpath(filename)
def generate_agrid(data: pd.DataFrame):
gb = GridOptionsBuilder.from_dataframe(data)
gb.configure_default_column(editable=True) # Make columns editable
gb.configure_pagination(paginationAutoPageSize=True) # Add pagination
gb.configure_side_bar() # Add a sidebar
gb.configure_selection('multiple', use_checkbox=True,
groupSelectsChildren="Group checkbox select children") # Enable multi-row selection
gridOptions = gb.build()
grid_response = AgGrid(
data,
gridOptions=gridOptions,
data_return_mode=DataReturnMode.AS_INPUT,
update_on='MANUAL', # <- Should it let me update before returning?
fit_columns_on_grid_load=False,
theme=AgGridTheme.STREAMLIT, # Add theme color to the table
enable_enterprise_modules=True,
height=350,
width='100%',
reload_data=True
)
data = grid_response['data']
selected = grid_response['selected_rows']
df = pd.DataFrame(selected) # Pass the selected rows to a new dataframe df
return grid_response
def onAddRow(grid_table):
df = pd.DataFrame(grid_table['data'])
column_fillers = {
column: (False if df.dtypes[column] == "BooleanDtype"
else 0 if df.dtypes[column] == "dtype('float64')"
else '' if df.dtypes[column] == "string[python]"
else datetime.datetime.utcnow() if df.dtypes[column] == "dtype('<M8[ns]')"
else '')
for column in df.columns
}
data = [column_fillers]
df_empty = pd.DataFrame(data, columns=df.columns)
df = pd.concat([df, df_empty], axis=0, ignore_index=True)
grid_table = generate_agrid(df)
return grid_table
# First data gather
df = get_data()
if __name__ == '__main__':
# Start graphing
grid_table = generate_agrid(df)
# add row
st.sidebar.button("Add row", on_click=onAddRow, args=[grid_table])
Here is a sample minimal code.
import streamlit as st
import pandas as pd
from st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode
def generate_agrid(df):
gb = GridOptionsBuilder.from_dataframe(df)
gb.configure_selection(selection_mode="multiple", use_checkbox=True)
gridoptions = gb.build()
grid_response = AgGrid(
df,
height=200,
gridOptions=gridoptions,
update_mode=GridUpdateMode.MANUAL
)
selected = grid_response['selected_rows']
# Show the selected row.
if selected:
st.write('selected')
st.dataframe(selected)
return grid_response
def add_row(grid_table):
df = pd.DataFrame(grid_table['data'])
new_row = [['', 100]]
df_empty = pd.DataFrame(new_row, columns=df.columns)
df = pd.concat([df, df_empty], axis=0, ignore_index=True)
# Save new df to sample.csv.
df.to_csv('sample.csv', index=False)
def get_data():
"""Reads sample.csv and return a dataframe."""
return pd.read_csv('sample.csv')
if __name__ == '__main__':
df = get_data()
grid_response = generate_agrid(df)
st.sidebar.button("Add row", on_click=add_row, args=[grid_response])
Initial output
Output after pressing add row
sample.csv
team,points
Lakers,120
Celtics,130
Thanks all for your suggestions. Adding self. before calling my functions fixed that issue. I'm now running into a different issue where the stored procedure I am using isn't getting properly read into the pandas dataframe. I don't get any errors, the tkinter window pops up like it should, but when the PDF gets generated, there is no data in the rows, just the column names and other formatting I've written in.
I added print(df) to the code to check if it was an issue with the data getting read from the dataframe to the PDF, but print(df) just returns Empty DataFrame.
from tkinter import *
import pyodbc
import pandas as pd
from reportlab.lib import colors
from reportlab.platypus import *
from reportlab.lib import styles
from reportlab.lib.units import inch
# Create connection
server = 'XXXXXXX'
database = 'XXXXXXX'
username = 'XXXXXXXX'
password = 'XXXXXXXXX'
try:
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+password+'')
except:
raise NameError('unable to connect')
#save stored procedure to a global variable
storedProc = 'EXEC [presentation].[pdf_project] '
elements = []
class NewPDF:
def __init__(self):
window = tk.Tk()
window.title("Form Example")
window = tk.Frame(window)
window.grid(column=0,row=0, sticky=(tk.N,tk.W,tk.E,tk.S))
window.columnconfigure(0, weight = 1)
window.rowconfigure(0, weight = 1)
window.pack(pady = 100, padx = 100)
self.tkvar = tk.StringVar(window)
choices = {'2021','2020','2019','2018'}
self.tkvar.set('2021')
popupMenu = tk.OptionMenu(window, self.tkvar, *choices)
tk.Label(window, text = "Pick Year").grid(row = 1, column = 1)
popupMenu.grid(row = 1, column = 2)
tk.Label(window, text = "Customer").grid(row = 2, column = 1)
self.e1 = tk.Entry(window)
self.e1.grid(row = 2, column = 2)
self.param_year = self.tkvar.get()
self.param_cust = str(self.e1.get())
B = tk.Button(window, text = "Make PDF", command=self.make_df_and_pdf()).grid(row = 3, column = 1)
self.tkvar.trace('w', self.change_dropdown())
window.mainloop()
def change_dropdown(self, *args):
print(args)
def make_df_and_pdf(self):
#param_year = self.tkvar.get()
#param_cust = str(self.e1.get())
params = "'" + self.param_cust + "'," + self.param_year + ""
querystring = storedProc + params
df = pd.read_sql_query(querystring, cnxn)
lista = [df.columns[:,].values.astype(str).tolist()] + df.values.tolist()
#cust_list = (df['CUSTOMER'].unique())
#cust_list = cust_list.tolist()
#print(df)
styles = getSampleStyleSheet()
ts = [('ALIGN', (1,1), (-1,1), 'LEFT'),
('BOX', (0,0), (3,0), 2, colors.red),
('FONT', (0,0), (-1,0), 'Times-Bold'),
('GRID', (0,1), (-1,-1), 0.5, colors.grey)]
n_table = Table(lista, colWidths = (1.5*inch, 1.5*inch, 1.5*inch, 1.5*inch, 1.5*inch), repeatRows = 1)
table_style = TableStyle(ts)
n_table.setStyle(table_style)
PATH_OUT = "Desktop"
doc = SimpleDocTemplate(PATH_OUT + 'UserInputPDF_Test.pdf')
elements.append(Paragraph("CustomerTAT", styles['Title']))
elements.append(n_table)
doc.build(elements)
NewPDF()
EDIT: The stored procedure operates as it should within SQL. Here is the code for my stored procedure:
USE [XXXXX]
GO
/****** Object: StoredProcedure [presentation].[pdf_project] Script Date: 6/22/2021 4:31:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: XXXXXX
-- Create date:
-- Description:
-- =============================================
ALTER PROCEDURE [presentation].[pdf_project]
-- Add the parameters for the stored procedure here
#CustomerName varchar(50) = '',
#Year int = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT CUSTOMER, [TAT Whole Days], [SHIP DATE], YEAR([SHIP DATE]) AS YEAR,
CASE
WHEN MONTH([SHIP DATE]) IN (1,2,3) THEN 'Q1'
WHEN MONTH([SHIP DATE]) IN (4,5,6) THEN 'Q2'
WHEN MONTH([SHIP DATE]) IN (7,8,9) THEN 'Q3'
ELSE 'Q4'
END AS QUARTER
FROM presentation.CustomerTAT
WHERE (YEAR([SHIP DATE]) = #Year or YEAR([SHIP DATE]) = #Year)
AND CUSTOMER = #CustomerName
END
I'm creating a table interface in which the user will receive a table from pandastable and write some data. Then, I need to save the updated pandastable to make some evaluations. How could I do this?
This is the code:
from tkinter import *
from pandastable import Table, TableModel
import pandas as pd
class TestApp(Frame):
def __init__(self, parent=None):
self.parent = parent
Frame.__init__(self)
self.main = self.master
self.main.geometry('600x400+200+100')
self.main.title('Table app')
f = Frame(self.main)
f.pack(fill=BOTH,expand=1)
df = pd.read_excel('2018.xlsx','November',7)
x = 'desc'
nome = df[x].values.tolist()
name = []
for i in range(len(nome)):
if nome[i] == nome[i] and nome[i] != x:
name.append(nome[i])
df1 = pd.DataFrame({x:name})
cfop = [float('Nan') for i in range(len(name))]
cst_in = [float('Nan') for i in range(len(name))]
cst_out = [float('Nan') for i in range(len(name))]
ncm = [float('Nan') for i in range(len(name))]
icms = [float('Nan') for i in range(len(name))]
df1['ncm'] = pd.Series(ncm)
df1['CST in'] = pd.Series(cst_in)
df1['CST out'] = pd.Series(cst_out)
df1['CFOP'] = pd.Series(cfop)
df1['ICMS'] = pd.Series(icms)
self.table = pt = Table(f, dataframe=df1, showtoolbar=True, showstatusbar=True)
pt.show()
return
app = TestApp()
app.mainloop()
df1 = Table.model.df1
The user is expected to fill the columns ncm, CFOP, ICMS, CST in and CST out. Right now, he can write on those columns, but the data is lost once he closes the app. I want to get the data that he writes and put in a variable DataFrame.
You can use the following line:
pt.doExport(filename="test2.csv")
This will result in a .csv file with all of the data from the table.
I am creating a custom file chooser in tkinter. I am creating a grid of checkbuttons representing files in a directory. Right now all i want to do is get a list of the file names a user chooses. As of now my code displays the gui nicely but when I try to determine what boxes the user checked it's not working. I'm not sure what I'm doing wrong. Most likely in the way i'm setting the variable for the checkbutton. I know this would be easy for a python pro but i'm not a pro so any help would be greatly appreciated. See my code below. Apologies ahead of time for the huge amount of code but i'm not sure where i'm going wrong so i put it all in.
Mark
class scareGUI:
def __init__(self, master):
self.selectedFileName = StringVar()
#filter non video file types
includes = ['*.mp4','*.py']
includes = r'|'.join([fnmatch.translate(x) for x in includes])
#master.attributes('-zoomed', True)
self.frame_header = ttk.Frame(master)
self.frame_header.pack()
ttk.Label(self.frame_header, text="TerrorForm ScareBox").grid(row=0, column = 0, rowspan = 2)
self.frame_files = ttk.Frame(master)
self.frame_files.pack()
self.frame_footer = ttk.Frame(master)
self.frame_footer.pack()
#pull file names from file system
for root, dirs, self.files in os.walk('./movies'):
self.files = [os.path.join(root, f) for f in self.files]
self.files = [f for f in self.files if re.match(includes, f)]
#Determine number of rows in grid
numfiles = len(self.files)
dividesBy = False
numRows = IntVar()
numColumns = 4
while (dividesBy == False):
if(numfiles % numColumns == 0):
numRows=int(numfiles/numColumns)
dividesBy = True
else:
numfiles+=1
#Print Check Boxes in Grid layout
filmIcon = PhotoImage(file='tf_film_icon.gif')
i=0
self.checkedFiles=[None]*len(self.files)
for r in range(numRows):
for c in range(4):
if (i<len(self.files)):
self.checkedFiles[i] = IntVar()
checkbutton = ttk.Checkbutton(self.frame_files, text=self.files[i], variable=self.checkedFiles[i])
checkbutton.config(image = filmIcon,compound = TOP)
checkbutton.image = filmIcon
checkbutton.grid(row = r, column = c)
i += 1
def getChosenFiles(self):
self.chosenFiles=[]
for x in range(len(self.files)):
if(self.checkedFiles[x].get()):
self.chosenFiles.append(self.files[x])
print (self.chosenFiles[0])
return self.chosenFiles
def main():
root = Tk()
scaregui = scareGUI(root)
root.mainloop()
if __name__ == "__main__": main()