Mundo em Python

Registar as Viagens (usando Tkinter)

from tkinter import *
import tkinter.ttk as ttk
import tkinter.messagebox as tkMessageBox
import sqlite3
def Database():
global conn, cursor
conn = sqlite3.connect("viagens.db")
cursor = conn.cursor()
cursor.execute(
"CREATE TABLE IF NOT EXISTS REGISTRATION (RID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, NOMEPAIS TEXT, "
"NOMECIDADE TEXT, DATAINICIO TEXT, DATAFINAL TEXT, TRANSPORTE TEXT )")
def DisplayForm():
root = Tk()
root.geometry("900x500")
root.title("Registar as Viagens")
global tree
global SEARCH
global Nome_pais,Nome_ciadade,datainicio,datafinal,transporte
SEARCH = StringVar()
Nome_pais = StringVar()
Nome_ciadade = StringVar()
datainicio = StringVar()
datafinal = StringVar()
transporte = StringVar()
TopViewForm = Frame(root, width=600, bd=1, relief=SOLID)
TopViewForm.pack(side=TOP, fill=X)
LFrom = Frame(root, width="350",bg="#15244C")
LFrom.pack(side=LEFT, fill=Y)
LeftViewForm = Frame(root, width=500,bg="#0B4670")
LeftViewForm.pack(side=LEFT, fill=Y)
MidViewForm = Frame(root, width=600)
MidViewForm.pack(side=RIGHT)
lbl_text = Label(TopViewForm, text="Registar as Viagens", font=('verdana', 18), width=600,bg="cyan")
lbl_text.pack(fill=X) # Nome_pais, Nome_ciadade, datainicio, datafinal, transporte
Label(LFrom, text="Nome do País ", font=("Arial", 12),bg="#15244C",fg="white").pack(side=TOP)
Entry(LFrom,font=("Arial",10,"bold"),textvariable=Nome_pais).pack(side=TOP, padx=10, fill=X)
Label(LFrom, text="Nome da Cidade ", font=("Arial", 12),bg="#15244C",fg="white").pack(side=TOP)
Entry(LFrom, font=("Arial", 10, "bold"),textvariable=Nome_ciadade).pack(side=TOP, padx=10, fill=X)
Label(LFrom, text="Data de Início ", font=("Arial", 12),bg="#15244C",fg="white").pack(side=TOP)
Entry(LFrom, font=("Arial", 10, "bold"),textvariable=datainicio).pack(side=TOP, padx=10, fill=X)
Label(LFrom, text="Data de Final ", font=("Arial", 12), bg="#15244C", fg="white").pack(side=TOP)
Entry(LFrom, font=("Arial", 10, "bold"), textvariable=datafinal).pack(side=TOP, padx=10, fill=X)
Label(LFrom, text="Transporte ", font=("Arial", 12),bg="#15244C",fg="white").pack(side=TOP)
transporte.set("Selecionar Transporte")
content={'Avião','Carro','Comboio','Autocarro'}
OptionMenu(LFrom,transporte,*content).pack(side=TOP, padx=10, fill=X) # ,command=actualizacao
Button(LFrom,text="Submeter",font=("Arial", 10, "bold"),bg="#15244C",fg="white",command=register).pack(side=TOP, padx=10,pady=5, fill=X) lbl_txtsearch = Label(LeftViewForm, text="Digite o Nome do País", font=('verdana', 10),bg="#0B4670")
lbl_txtsearch.pack()
search = Entry(LeftViewForm, textvariable=SEARCH, font=('verdana', 15), width=10)
search.pack(side=TOP, padx=10, fill=X)
btn_search = Button(LeftViewForm, text="Pesquisa",bg="cyan",command=SearchRecord)
btn_search.pack(side=TOP, padx=10, pady=10, fill=X)
btn_view = Button(LeftViewForm, text="Ver tudo",bg="cyan",command=DisplayData)
btn_view.pack(side=TOP, padx=10, pady=10, fill=X)
btn_Limpar = Button(LeftViewForm, text="Limpar",bg="cyan",command=limpar)
btn_Limpar.pack(side=TOP, padx=10, pady=10, fill=X)
btn_apagar = Button(LeftViewForm, text="Apagar",bg="cyan",command=apagar)
btn_apagar.pack(side=TOP, padx=10, pady=10, fill=X)
#create update button
btn_actualizar = Button(LeftViewForm, text="Actualizar",bg="cyan",command=actualizacao)
btn_actualizar.pack(side=TOP, padx=10, pady=10, fill=X)
#setting scrollbar


scrollbarx = Scrollbar(MidViewForm, orient=HORIZONTAL)
scrollbary = Scrollbar(MidViewForm, orient=VERTICAL)
tree = ttk.Treeview(MidViewForm,columns=("Student Id", "Nomepais",
"Nomeciadade","datainicio",
"datafinal","transporte"),
selectmode="extended", height=100,
yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
scrollbary.config(command=tree.yview)
scrollbary.pack(side=RIGHT, fill=Y)
scrollbarx.config(command=tree.xview)
scrollbarx.pack(side=BOTTOM, fill=X)
tree.heading('Student Id', text="Id", anchor=W)
tree.heading('Nomepais', text="Nome Pais", anchor=W)
tree.heading('Nomeciadade', text="Nome da Cidade", anchor=W)
tree.heading('datainicio', text="Data de Início", anchor=W)
tree.heading('datafinal', text="Data Final", anchor=W)
tree.heading('transporte', text="Transporte", anchor=W)
tree.column('#0', stretch=NO, minwidth=0, width=0)
tree.column('#1', stretch=NO, minwidth=0, width=150)
tree.column('#2', stretch=NO, minwidth=0, width=150)
tree.column('#3', stretch=NO, minwidth=0, width=150)
tree.column('#4', stretch=NO, minwidth=0, width=120)
tree.column('#5', stretch=NO, minwidth=0, width=80)
tree.pack()
def actualizacao():
Database()
vNome_pais = Nome_pais.get()
vNome_ciadade = Nome_ciadade.get()
vdatainicio = datainicio.get()
vdatafinal = datafinal.get()
vtransporte = transporte.get() if not all([vNome_pais, vNome_ciadade, vdatainicio, vdatafinal, vtransporte]):
tkMessageBox.showinfo("Atenção", "Preencha todos os espaços!!!")
else:
curItem = tree.focus()
contents = tree.item(curItem)
selecteditem = contents['values'] try:
conn.execute(
'UPDATE REGISTRATION SET NOMEPAIS=?, NOMECIDADE=?, DATAINICIO=?, DATAFINAL=?, TRANSPORTE=? WHERE RID=?',
(vNome_pais, vNome_ciadade, vdatainicio, vdatafinal, vtransporte, selecteditem[0]))
conn.commit()
tkMessageBox.showinfo("Mensagem", "Atualização com Sucesso")
limpar()
DisplayData()
except sqlite3.Error as e:
tkMessageBox.showerror("Erro", f"Erro ao atualizar o registro: {str(e)}")
finally:
conn.close()
def SearchRecord():
Database()
if SEARCH.get() != "":
tree.delete(*tree.get_children())
cursor=conn.execute("SELECT * FROM REGISTRATION WHERE NOMEPAIS LIKE ?", ('%' + str(SEARCH.get()) + '%',))
fetch = cursor.fetchall()
for data in fetch:
tree.insert('', 'end', values=(data))
cursor.close()
conn.close()
def apagar():
Database()
if not tree.selection():
tkMessageBox.showwarning("Atenção","Selecione a viagem a eliminar ")
else:
result = tkMessageBox.askquestion('Confirmar', 'Deseja apagar o registo da viagem?',
icon="warning")
if result == 'yes':
curItem = tree.focus()
contents = (tree.item(curItem))
selecteditem = contents['values']
tree.delete(curItem)
cursor=conn.execute("DELETE FROM REGISTRATION WHERE RID = %d" % selecteditem[0])
conn.commit()
cursor.close()
conn.close()
conn.close()
def OnDoubleClick(self):
curItem = tree.focus()
contents = (tree.item(curItem))
selecteditem = contents['values']
Nome_pais.set(selecteditem[1])
Nome_ciadade.set(selecteditem[2])
datainicio.set(selecteditem[3])
datafinal.set(selecteditem[4])
transporte.set(selecteditem[5])
def DisplayData():
Database()
tree.delete(*tree.get_children())
cursor=conn.execute("SELECT * FROM REGISTRATION")
fetch = cursor.fetchall()
for data in fetch:
tree.insert('', 'end', values=(data))
tree.bind("<Double-1>",OnDoubleClick)
cursor.close()
conn.close()
def register():
Database()
vNome_pais=Nome_pais.get()
vNome_ciadade=Nome_ciadade.get()
vdatainicio=datainicio.get()
vdatafinal=datafinal.get()
vtransporte = transporte.get()
if vNome_pais=='' or vNome_ciadade==''or vdatainicio=='' or vdatafinal==''or vtransporte=='':
tkMessageBox.showinfo("Atenção","Preencha os espaços vazios!!!")
else:
conn.execute('INSERT INTO REGISTRATION (NOMEPAIS,NOMECIDADE,DATAINICIO,DATAFINAL,TRANSPORTE) \
VALUES (?,?,?,?,?)',(vNome_pais,vNome_ciadade,vdatainicio,vdatafinal,vtransporte));
conn.commit() tkMessageBox.showinfo("Sucesso","Viagem adicionada com Sucesso")
DisplayData()
conn.close()
def limpar():
# Nome_pais, Nome_ciadade, datainicio, datafinal, transporte
tree.delete(*tree.get_children())
# DisplayData()
SEARCH.set("")
Nome_pais.set("")
Nome_ciadade.set("")
datainicio.set("")
datafinal.set("")
transporte.set("Selecionar Transporte") DisplayForm()
if __name__=='__main__':
mainloop()
0