前几天我问如何传递值,并被引导将gui输入发送到辅助脚本,但是从gui传递值后,我无法运行excel脚本。这里是脚本的链接。我需要重新制作Excel脚本吗?还是以其他方式运行所有内容?
Tkinter代码
#! /usr/bin/env python3
# ! GUI no class.py
from tkinter import *
import subprocess
from tkinter.ttk import *
from PIL import ImageTk, Image
from pprint import pprint
from tkcalendar import Calendar, DateEntry
from tkinter import filedialog
from GUI_DTS import get_data
from ttkthemes import ThemedTk
from os import path
window = Tk()
window.geometry('600x700')
window.title('Time Card Maker')
window.iconbitmap('Users/PyCharmProjects/TimeCardProject/tcicon.icns')
path = '/Users/Documents/PythonExcel'
cal = Calendar(day=0, date_pattern='mm-dd-yyyy')
cal.grid(column=1, row=3)
def choose_date():
def print_sel(event):
print(cal.get_date())
cal_label = Label(text=f'Chosen date is ' + cal.get_date()).grid(column=1, row=0)
cal.bind('<<CalendarSelected>>', print_sel)
# cal.grid(column=0, row=6)
# Add a file dialog (file and directory chooser)
def open_files():
global selected_file
selected_file = filedialog.askdirectory(initialdir=path)
dts_file_label = Label(text=f'Selected folder is {selected_file}').grid(column=1, row=1)
print(selected_file)
def submit():
selected_date = cal.get_date()
dts_folder = selected_file
def button_press():
selected_files_buttin.bind('<<Button-1>>', button_press)
get_data(selected_date, dts_folder)
app_title = Label(window, text='Let the app do the work!')
app_title.grid(column=1, row=0, columnspan=20)
select_files_button = Button(window, text='Choose Folder', command=open_files)
select_files_button.grid(column=0, row=2)
select_date = Button(window, text='Choose date!', command=choose_date)
select_date.grid(column=2, row=2)
submit_button = Button(window, text='Submit date and folder', command=submit)
submit_button.grid(column=1, row=4)
quit_button = Button(window, text='Quit', command=window.quit)
quit_button.grid(column=1, row=5)
style = Style()
style.theme_use('default')
style.configure("black.Horizontal.TProgressbar", background='black')
# Add a progressbar widget, and change the color
style = Style()
style.theme_use('default')
style.configure("black.Horizontal.TProgressbar", background = 'black')
bar = Progressbar(window, length = 200, style = 'black.Horizontal.TProgressbar')
bar = Progressbar(window, length = 200)
bar.grid(column=1, row=2)
# Last line
window.mainloop()
Excel脚本 这是excel脚本,如果可以从中受益,可以进行任何更改。
#! /usr/bin/env python3
#! GUI_DTS.py
# chmod +x DTS_to_Weekly.py
# Imports
import pandas as pd
import os
from pathlib import Path
import glob
import xlrd
import openpyxl
import pprint
import datetime
import time
from employee_data_base import employee_db as db
from openpyxl.styles import Font, Alignment
if __name__ == "__main__":
main()
start = time.time()
# dts_folder = ('/Users/Documents/PythonExcel/DTS/')
template_loc = '/Users/Documents/PythonExcel'
template_file = 'TCBlank.xlsx'
re_rates = [{'Position': 'Condor Op', 'Code': '5431'}, {'Position': 'S/O', 'Code': '5431'}]
occ_codes = {'CLT': '5401', 'ACLT': '5403', 'LCP': '5422', 'SLT': '5451', 'Condor Op': '5431', 'S/O': '5431'}
# xlsx_files = [path for path in Path(dts_folder).rglob('*.xlsx')]
def read_files(file):
global xlsx_files
xlsx_files = [path for path in Path(file).rglob('*.xlsx')]
return xlsx_files
import_dts()
# Import individual daily time sheets
def import_dts():
col_names = ['Name', 'Position', 'Call', 'Lunch In', 'Lunch Out', 'Wrap']
cols = [1, 2, 4, 5, 7, 8]
skiprows = [0, 1, 2, 3, 21, 22, 23, 25, 25]
df = pd.DataFrame()
pd.set_option('max_r', None)
pd.set_option('display.max_columns', None)
df = pd.concat([pd.read_excel(f, usecols=cols, skiprows=skiprows, names=col_names,
header=None).assign(Date=os.path.basename(f)) for f in xlsx_files])
df['Date'] = df['Date'].str.rstrip(' DTS.xlsx')
df = df.dropna()
create_df_dict(df)
return df
# Create dictionary from combined data frame
def create_df_dict(df):
df_dict = df.to_dict('r')
names_list()
# Create list of employee names
def names_list():
global employee_names
employee_names = sorted(list(set(df['Name'])))
for n in employee_names:
fl = n.split(" ")
first_name = fl[0]
last_name = fl[1]
lf_name = []
lf_name.append(f'{last_name}, {first_name}')
print(lf_name)
create_workbooks()
# Create workbook for weekly data
def create_workbooks():
os.chdir(template_loc)
global wb
wb = openpyxl.load_workbook(template_file, data_only=True)
ws = wb.active
return wb
get_dates()
# Get the week ending date to fill in cell and then excel fills in the rest of the week column
def get_dates(date):
global template
global weekEndDate
template = wb['TC_Template']
print('What is the week ending date?')
# endDate = input()
# global end_date
# global weekEndDate
# end_date = '03-07-2020'
# gui_end_date = cal
# weekEndDate = pd.date_range(end=end_date, periods=7)
weekEndDate = pd.date_range(end=selected_date, periods=7)
name_wtc()
# Name weekly time card file
def name_wtc():
global weekly_tc
# weekly_tc = f"/Users/Documents/PythonExcel/WeeklyTimeCard {end_date}.xlsx"
weekly_tc = f"/Users/Documents/PythonExcel/WeeklyTimeCard {gui_files}.xlsx"
fill_date_cells()
# Write dates to cells
def fill_date_cells():
template['F15'].value = weekEndDate[0].strftime('%m-%d')
template['F17'].value = weekEndDate[1].strftime('%m-%d')
template['F19'].value = weekEndDate[2].strftime('%m-%d')
template['F21'].value = weekEndDate[3].strftime('%m-%d')
template['F23'].value = weekEndDate[4].strftime('%m-%d')
template['F25'].value = weekEndDate[5].strftime('%m-%d')
template['F27'].value = weekEndDate[6].strftime('%m-%d')
template['AE6'].value = weekEndDate[6].strftime('%m-%d-%y')
template_copier()
print('Finished updating the template')
# Create sheets for each person from template
def template_copier():
for copies in range(len(employee_names)):
target = wb.copy_worksheet(from_worksheet=template)
rename_sheets()
print('Copied sheets!')
# Rename the sheets based on the name of the person
def rename_sheets():
sheets = wb.sheetnames
counter = 0
for sheet in sheets:
ss_sheet = wb[sheet]
ss_sheet.title = employee_names[counter - 1]
ss_sheet['B8'].value = employee_names[counter - 1]
counter += 1
wb.save(weekly_tc)
dup_delete()
print('Sheets renamed!')
# Delete duplicate sheet
def dup_delete():
list_sheets = list(wb.sheetnames)
list_sheets_len = len(list_sheets) - 1
dup_sheet = list_sheets[list_sheets_len]
del wb[dup_sheet]
wb.save(weekly_tc)
print('Finished creating all the sheets!')
load_wtc()
def load_wtc():
global wtc_wb
wtc_wb = openpyxl.load_workbook(weekly_tc)
# write_tc(emp)
run_program()
# Function to match up employee weekly data and write it into the excel time card
def write_tc(emp):
ws1 = wtc_wb[emp]
name_cell = ws1['B8'].value
sunday = ws1['F15'].value
monday = ws1['F17'].value
tuesday = ws1['F19'].value
wednesday = ws1['F21'].value
thursday = ws1['F23'].value
friday = ws1['F25'].value
saturday = ws1['F27'].value
for d in df_dict:
if d['Name'] == name_cell and d['Date'] == sunday:
ws1['I15'].value = d['Call']
ws1['J15'].value = d['Lunch In']
ws1['K15'].value = d['Lunch Out']
ws1['O15'].value = d['Wrap']
elif d['Name'] == f"{name_cell}" and d['Date'] == monday:
ws1['I17'].value = d['Call']
ws1['J17'].value = d['Lunch In']
ws1['K17'].value = d['Lunch Out']
ws1['O17'].value = d['Wrap']
elif d['Name'] == f"{name_cell}" and d['Date'] == tuesday:
ws1['I19'].value = d['Call']
ws1['J19'].value = d['Lunch In']
ws1['K19'].value = d['Lunch Out']
ws1['O19'].value = d['Wrap']
elif d['Name'] == f"{name_cell}" and d['Date'] == wednesday:
ws1['I21'].value = d['Call']
ws1['J21'].value = d['Lunch In']
ws1['K21'].value = d['Lunch Out']
ws1['O21'].value = d['Wrap']
elif d['Name'] == f"{name_cell}" and d['Date'] == thursday:
ws1['I23'].value = d['Call']
ws1['J23'].value = d['Lunch In']
ws1['K23'].value = d['Lunch Out']
ws1['O23'].value = d['Wrap']
elif d['Name'] == f"{name_cell}" and d['Date'] == friday:
ws1['I25'].value = d['Call']
ws1['J25'].value = d['Lunch In']
ws1['K25'].value = d['Lunch Out']
ws1['O25'].value = d['Wrap']
elif d['Name'] == f"{name_cell}" and d['Date'] == saturday:
ws1['I27'].value = d['Call']
ws1['J27'].value = d['Lunch In']
ws1['K27'].value = d['Lunch Out']
ws1['O27'].value = d['Wrap']
# print(f"Finished writing {emp}'s time card!")
# Fill in position code and last four of social
def fill_position(emp):
global ws1
ws1 = wtc_wb[emp]
name_cell = ws1['B8'].value
sig = ws1['E45']
sig.font = Font(bold=False, name='Brush Script MT', size=36)
sig.alignment = Alignment(indent=1, horizontal='left', vertical='center')
ss_cell = ws1['O8'].value
position_cell = ws1['AM10'].value
for i in db:
if i['name'] == name_cell:
ws1['O8'].value = i['social']
ws1['AM10'].value = i['position']
sig.value = i['name']
# print(f"{emp} social and position filled in! Now filling in their times!")
def check_rerates(emp):
global ws1
ws1 = wtc_wb[emp]
name_cell = ws1['B8'].value
sunday = ws1['F15'].value
monday = ws1['F17'].value
tuesday = ws1['F19'].value
wednesday = ws1['F21'].value
thursday = ws1['F23'].value
friday = ws1['F25'].value
saturday = ws1['F27'].value
position_cell = ws1['AM10'].value
for d in df_dict:
for p in re_rates:
if d['Position'] == p['Position'] and d['Name'] == name_cell and d['Date'] == sunday:
ws1['P15'].value = p['Position']
ws1['Q15'].value = p['Code']
print(f"{emp} was re-rated to {p['Position']} on Sunday.")
elif d['Position'] == p['Position'] and d['Name'] == name_cell and d['Date'] == monday:
ws1['P17'].value = p['Position']
ws1['Q17'].value = p['Code']
print(f"{emp} was re-rated to {p['Position']} on Monday.")
elif d['Position'] == p['Position'] and d['Name'] == name_cell and d['Date'] == tuesday:
ws1['P19'].value = p['Position']
ws1['Q19'].value = p['Code']
print(f"{emp} was re-rated to {p['Position']} on Tuesday.")
elif d['Position'] == p['Position'] and d['Name'] == name_cell and d['Date'] == wednesday:
ws1['P21'].value = p['Position']
ws1['Q21'].value = p['Code']
print(f"{emp} was re-rated to {p['Position']} on Wednesday.")
elif d['Position'] == p['Position'] and d['Name'] == name_cell and d['Date'] == thursday:
ws1['P23'].value = p['Position']
ws1['Q23'].value = p['Code']
print(f"{emp} was re-rated to {p['Position']} on Thursday.")
elif d['Position'] == p['Position'] and d['Name'] == name_cell and d['Date'] == friday:
ws1['P25'].value = p['Position']
ws1['Q25'].value = p['Code']
print(f"{emp} was re-rated to {p['Position']} on Friday.")
elif d['Position'] == p['Position'] and d['Name'] == name_cell and d['Date'] == saturday:
ws1['P27'].value = p['Position']
ws1['Q27'].value = p['Code']
print(f"{emp} was re-rated to {p['Position']} on Saturday.")
# Get values from GUI
def get_data(dts_folder, selected_date):
date = selected_date
file = dts_folder
read_files(file)
get_dates(date)
# run_program()
# use the passed in arguments to do the work, not the hardcoded globals
def run_program():
for emp in employee_names:
fill_position(emp)
write_tc(emp)
print(f"Finished writing {emp} time card!")
check_rerates(emp)
wtc_wb.save(weekly_tc)
# wtc_wb.save(weekly_tc)
print('It took', time.time()-start, 'seconds.')