Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
victordomingos authored Feb 23, 2018
1 parent f268744 commit e882ade
Show file tree
Hide file tree
Showing 5 changed files with 154 additions and 59 deletions.
3 changes: 1 addition & 2 deletions ctt_tracking/about_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def __init__(self):


#---------- FUNDO -----------
copyright_lbl = ttk.Label(pframe_fundo, font=copyfont, text="\n© 2017 Victor Domingos")
copyright_lbl = ttk.Label(pframe_fundo, font=copyfont, text="\n© 2018 Victor Domingos")
license_lbl = ttk.Label(pframe_fundo, font=copyfont, text=__license__)


Expand All @@ -171,7 +171,6 @@ def __init__(self):
popupRoot.mainloop()



def thanks(*event):
janela_thanks = thanks_window()

Expand Down
100 changes: 60 additions & 40 deletions ctt_tracking/callbacks_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import os
import webbrowser
import shlex
import logging

from tkinter import ttk, messagebox
from datetime import time, datetime, timedelta
Expand All @@ -29,7 +30,6 @@ def __init__(self, oop):
def expedir_select(self, event):
self.oop.combo_expedidor.selection_clear()


def atualizacao_periodica(self):
""" Atualiza automaticamente de forma periódica a informação com o
estado atual das remessas ativas. Caso a interface não esteja
Expand All @@ -41,27 +41,30 @@ def atualizacao_periodica(self):

agora = datetime.now()
agora_hora = agora.time()

if time(9,30) <= agora_hora <= time(20,00):
self.oop.updates +=1

print("atualizacao_periodica() em curso... ", datetime.now().time(), "-", self.oop.updates)
self.oop.progressbar.show_progress(value=20, mode="determinate")
logging.debug("atualizacao_periodica() em curso... -" + str(self.oop.updates))
s_status = "A obter estados atualizados para as remessas em curso."
self.oop.status_txt.set(s_status)
db_atualizar_tudo()
self.oop.progressbar.progress_update(60)
criar_mini_db()

self.oop.progressbar.progress_update(80)
s_status = "Atualização completa!"
self.oop.status_txt.set(s_status)

# apenas atualizar a tabela com os novos dados, caso não esteja em curso uma operação do utilizador:
if (not self.oop.detalhe_visible) and (not self.oop.entryform_visible) and (not self.oop.pesquisa_visible):
self.regressar_tabela()

self.oop.progressbar.hide_progress(last_update=100)
# Agendar nova atualização apenas até ser atingido o seguinte limite:
if self.oop.updates <= 900:
self.oop.mainframe.after(update_delay, self.atualizacao_periodica)

else:
print("atualizacao_periodica(): Fora do horário de serviço. Atualização adiada.", agora_hora)
logging.debug("atualizacao_periodica(): Fora do horário de serviço. Atualização adiada.")

def nada(self, *event):
""" # Hacking moment: Uma função que não faz nada, para quando isso dá jeito...
Expand Down Expand Up @@ -102,10 +105,10 @@ def popupMenu(self, event):
self.oop.tree.focus(iid)
self.oop.contextMenu.post(event.x_root, event.y_root)
#print("popupMenu(): x,y = ", event.x_root, event.y_root)
else:
print("popupMenu(): wrong values for event - x=0, y=0")
#else:
# print("popupMenu(): wrong values for event - x=0, y=0")
else:
print("popupMenu(): Else - No code here yet! (mouse not over item)")
#print("popupMenu(): Else - No code here yet! (mouse not over item)")
# mouse pointer not over item
# occurs when items do not fill frame
# no action required
Expand Down Expand Up @@ -302,9 +305,12 @@ def ativar_emcurso(self, *event):
self.oop.text_input_pesquisa.delete(0, END)

if self.oop.updates:
self.oop.progressbar.show_progress(value=20, mode="determinate")
db_atualizar_tudo()
self.oop.progressbar.progress_update(60)
criar_mini_db()
self.oop.updates += 1
self.oop.progressbar.hide_progress(last_update=100)

conn = sqlite3.connect(DB_PATH, detect_types=sqlite3.PARSE_DECLTYPES)
c = conn.cursor()
Expand Down Expand Up @@ -1104,8 +1110,9 @@ def copiar_lista_por_expedidor(self, event=None):
resumo_mes = resumo_mes + txt_mes_remessas + txt_mes_num_vols + txt_mes_simples + txt_mes_multiplos + txt_mes_num_cobr + "\n\n"
texto_completo_expedidor += resumo_mes

else:
print("nem é a primeira remessa do mês, nem chegou o fim do mês!", linha_atual, linha_atual_expedidor, num_remessas)
#else:
# print("nem é a primeira remessa do mês, nem chegou o fim do mês!",
# linha_atual, linha_atual_expedidor, num_remessas)

linha_atual = 0
if (linha_atual_expedidor != num_remessas-1): # Se é a primeira remessa do mês, mostra a data.
Expand Down Expand Up @@ -1312,8 +1319,8 @@ def clear_text(self):
self.oop.text_input_obs.delete(0, END)
self.oop.combo_expedidor.current(INDEX_EXPEDIDOR_PREDEFINIDO)
except Exception as e:
print("This is a very misterious clear_text() error! But what kind of program would be happy without having some kind of bug like this?...")
print("Exception:", e)
logging.debug("This is a very misterious clear_text() error! But what kind of program would be happy without having some kind of bug like this?...")
logging.debug("Exception: "+ str(e))


def show_entryform(self, *event):
Expand Down Expand Up @@ -1363,7 +1370,7 @@ def atualizar_remessa_selecionada(self):
try:
tree_obj_num = tree_linha["values"][3]
except Exception as e:
print("self.atualizar_remessa_selecionada() > Exception:", e)
logging.debug("self.atualizar_remessa_selecionada() > Exception:" +str(e))
self.oop.remessa_selecionada = ""
messagebox.showwarning("", "Nenhuma remessa selecionada.")
self.oop.master.focus_force()
Expand All @@ -1386,7 +1393,7 @@ def mostrar_detalhe(self, *event):
self.hide_entryform()
self.atualizar_remessa_selecionada()

print("Remessa selecionada:", self.oop.remessa_selecionada)
logging.debug("Remessa selecionada: " + str(self.oop.remessa_selecionada))
db_update_estado(self.oop.remessa_selecionada)

conn = sqlite3.connect(DB_PATH)
Expand All @@ -1398,8 +1405,8 @@ def mostrar_detalhe(self, *event):
detalhes = c.fetchone()
conn.commit()
c.close()
print(f"Detalhes ({type(detalhes)}):")
print(detalhes)
logging.debug((f"Detalhes ({type(detalhes)}):"))
logging.debug(detalhes)

#db_id = detalhes[0] # INTEGER PRIMARY KEY AUTOINCREMENT,
destin = detalhes[1] # TEXT NOT NULL,
Expand Down Expand Up @@ -1445,8 +1452,8 @@ def mostrar_detalhe(self, *event):
estado_detalhado = json.loads(detalhes[16]) # json
use_terminaltables = False
except Exception as e:
print(e)
estado_detalhado = json.detalhes[16] # TEXT (old terminaltables version)
logging.debug(e)
estado_detalhado = detalhes[16] # TEXT (old terminaltables version)
use_terminaltables = True

self.oop.dfl_remessa = ttk.Label(self.oop.detalheframe, style="BW.TLabel", text="Detalhes da Remessa: {}\n".format(destin))
Expand Down Expand Up @@ -1489,9 +1496,9 @@ def mostrar_detalhe(self, *event):
self.oop.dfl_data_depositar.grid(column=2, row=2, sticky='w')
self.oop.dfl_data_depositado.grid(column=2, row=3, sticky='w')

#ttk.Separator(self.oop.detalheframe).grid(column=0, row=7, pady=14, padx=3, columnspan=7, sticky='we')

if use_terminaltables:
ttk.Separator(self.oop.detalheframe).grid(column=0, row=7, pady=14, padx=3, columnspan=7, sticky='we')
self.oop.S = AutoScrollbar(self.oop.detalheframe)
self.oop.T = Text(self.oop.detalheframe, height=19, width=100)
self.oop.S.grid(column=7, row=8, sticky='wns')
Expand All @@ -1501,60 +1508,73 @@ def mostrar_detalhe(self, *event):
self.oop.T.insert(END, estado_detalhado, 'tabela')
self.oop.T.tag_config('tabela', foreground='#476042', justify="center", font=('Andale Mono', 12, 'bold'))
else:
if len(estado_detalhado) < 15:
altura = len(estado_detalhado)-3
linhas = len(estado_detalhado) - estado_detalhado.count([])

if linhas < 15:
altura = linhas
else:
altura = 15
self.oop.tree_detalhe = ttk.Treeview(self.oop.detalheframe, height=altura, selectmode='browse')
self.oop.tree_detalhe['columns'] = ('Data/Hora', 'Estado', 'Motivo', 'Local', 'Recetor')
self.oop.tree_detalhe['columns'] = ('Hora', 'Estado', 'Motivo', 'Local', 'Recetor')
self.oop.tree_detalhe.column('#0', anchor=W, minwidth=0, stretch=0, width=0)
self.oop.tree_detalhe.column('Data/Hora', anchor=E, minwidth=100, stretch=1, width=120)
self.oop.tree_detalhe.column('Estado', minwidth=100, stretch=1, width=130)
self.oop.tree_detalhe.column('Hora', anchor=E, minwidth=105, stretch=0, width=105)
self.oop.tree_detalhe.column('Estado', minwidth=120, stretch=1, width=130)
self.oop.tree_detalhe.column('Motivo', minwidth=110, stretch=1, width=130)
self.oop.tree_detalhe.column('Local', anchor=E, minwidth=100, stretch=1, width=130)
self.oop.tree_detalhe.column('Recetor', anchor=E, minwidth=100, stretch=1, width=120)
self.oop.tree_detalhe.column('Local', minwidth=100, stretch=1, width=130)
self.oop.tree_detalhe.column('Recetor', minwidth=100, stretch=1, width=120)

# Ordenar por coluna ao clicar no respetivo cabeçalho
for col in self.oop.tree_detalhe['columns']:
self.oop.tree_detalhe.heading(col, text=col.title(),
command=lambda c=col: self.sortBy(self.oop.tree_detalhe, c, 0))

# Barra de deslocação para a tabela
self.oop.tree_detalhe.grid(column=0, columnspan=7, row=8, sticky=N+W+E, in_=self.oop.detalheframe)
self.oop.tree_detalhe.grid(column=0, columnspan=7, row=8, sticky=N+W+E,
in_=self.oop.detalheframe, padx=10, pady="20 0")
vsb = AutoScrollbar(orient="vertical", command=self.oop.tree_detalhe.yview)
self.oop.tree_detalhe.configure(yscrollcommand=vsb.set)
vsb.grid(column=1, row=0, sticky=N+S, in_=self.oop.detalheframe)
self.oop.detalheframe.grid_columnconfigure(0, weight=1)
self.oop.detalheframe.grid_rowconfigure(0, weight=1)
ttk.Style().configure('Treeview', font=("Lucida Grande", 11), foreground="grey22", rowheight=20)
ttk.Style().configure('Treeview.Heading', font=("Lucida Grande", 11), foreground="grey22")

ttk.Style().configure('Treeview.Heading', font=("Lucida Grande", 11),
foreground="grey22")
ttk.Style().configure( '.', relief = 'flat', borderwidth = 0) # Aplicar visual limpo a todas as classes

self.oop.tree_detalhe.grid(column=0, columnspan=7, row=8, sticky='wne', pady=20)
self.oop.tree_detalhe.grid(column=0, columnspan=7, row=8, sticky='wne', pady="20 0")


print("------\n", estado_detalhado, type(estado_detalhado), "\n::::::::")
tag=""
for l in estado_detalhado[2:]:
print("LINE:", l)
if len(l) == 0:
continue
if len(l) > 1:
data = l[0]
hora = l[0]
estado = l[1]
motivo = l[2]
local = l[3]
recetor = l[4]
tag = ""
else:
data = l[0]
estado = ""
if comeca_por_dia_da_semana(l[0]):
dia_da_semana, data_extenso = l[0].replace("\n", " ").split(", ")
hora = dia_da_semana.capitalize()
estado = data_extenso
tag = "data"
else:
hora = ""
estado = ""
tag=""
motivo = ""
local = ""
recetor = ""

self.oop.tree_detalhe.insert("", 1, text ="Texto_nao_sei_que",
values=(data, estado, motivo, local, recetor))
self.oop.tree_detalhe.update()
self.oop.tree_detalhe.insert("", 1, text ="Texto_nao_sei_que", tag=tag,
values=(hora, estado, motivo, local, recetor))

self.oop.tree_detalhe.tag_configure('data', background="#CCDDFF", font=("Lucida "
"Grande Bold",
12))
self.oop.tree_detalhe.update_idletasks()


self.oop.btn_fechar_det = ttk.Button(self.oop.detalheframe, text="Fechar", command=self.hide_detalhe)
Expand Down
5 changes: 3 additions & 2 deletions ctt_tracking/ctt_tracking.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def __init__(self, master):
self.master.createcommand('exit', save_and_exit)
master.title(__app_name__+ " - "+ __version__)
master.minsize(width=800, height=600)
master.maxsize(width=1024, height=2000)
#master.maxsize(width=1024, height=2000)

self.callBacks = Callbacks(self) # Vai buscar ao módulo externo os métodos que pertenciam a esta classe.

Expand Down Expand Up @@ -269,6 +269,7 @@ def __init__(self, master):

# Painel de informação (entre a tabela e o formulário de entrada de dados) ------------------------------------
self.statusframe = ttk.Frame(root, padding="5 5 5 5")
self.progressbar = NPKProgressBar(self.statusframe)

self.statusFont = tkinter.font.Font(family="Lucida Grande", size=11)
self.statusbar = ttk.Label(self.statusframe, font=self.statusFont, foreground=self.btnTxtColor, textvariable=self.status_txt)
Expand Down Expand Up @@ -308,7 +309,7 @@ def __init__(self, master):
print("* ", end="", flush=True)
root.configure(background='grey95')
print("* ", end="", flush=True)
root.geometry('860x650')
root.geometry('860x650+0+0')
print("* ", end="", flush=True)
janela = Janela(root)
print("*", end="", flush=True)
Expand Down
68 changes: 68 additions & 0 deletions ctt_tracking/extra_tk_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,71 @@ def pack(self, **kw):
def place(self, **kw):
raise TclError("cannot use place with this widget")


class NPKProgressBar(ttk.Frame):
""" Simple Progress Bar class with custom methods.
"""
def __init__(self, master):
ttk.Frame.__init__(self, master)
self.master = master
self.progress_value = 0

self.progress_bar = ttk.Progressbar(self,
length=100,
mode='indeterminate')

self.place(in_=self.master, relx=1, rely=1, y=-10, anchor='e')


def show_progress(self, max_value=100, value=0, length=100, mode='indeterminate'):
""" Display a progress bar in the right side of the status bar. It
can accept a different maximum value, if needed. Mode must be
either "determinate" (it will display a real progress bar that
can be updated), or "indeterminate" (it will display a simple
progress bar that does not show a specific value.
"""
self.progress_reset()
self.progress_bar['mode'] = mode
if length:
self.progress_bar['length'] = length
if mode == 'indeterminate':
self.progress_bar.start()
else:
self.progress_bar['maximum'] = max_value
self.progress_update(value)

self.progress_bar.pack(side='right', padx="0 14")
self.progress_bar.update()
self.place(in_=self.master, relx=1, rely=1, y=-6, x=10, anchor='e')
self.master.update()

def _hide_progress(self):
""" Do the actual hiding of the progress bar. """
self.progress_bar.stop()
self.place_forget()
self.progress_reset()

def hide_progress(self, last_update=None):
""" Reset the progress bar and hide it. Optionaly, it can show
momentaneously a final value, by providing a value to the
last_update argument.
"""
if last_update:
self.progress_update(last_update)
self.after(300, self._hide_progress)
else:
self._hide_progress()

def progress_update(self, value):
""" Make the progress bar advance by indicating its new value. """
if value > self.progress_value:
self.progress_value = value
self.progress_bar['value'] = self.progress_value
self.progress_bar.update()
self.progress_bar.after(150, lambda: self.progress_update(self.progress_value+1))

def progress_reset(self):
""" Make the progress bar go back to zero. """
self.progress_value = 0
self.progress_bar['value'] = 0
self.progress_bar.update()
Loading

0 comments on commit e882ade

Please sign in to comment.