Ajouter une classe pour une application (Python 2.7/Tkinter)

Messages postés
1
Date d'inscription
lundi 29 avril 2019
Statut
Membre
Dernière intervention
29 avril 2019
-
Bonjour, j'espère que vous allez bien.
Mon problème cet que j'ai réalisée une application de gestion des erreurs par (Python2.7 et Tkinter) et j'ai utilisée seulement les fonction dans mon code alors je veux ajouter une classe pour mon scripte code pour le rappeler
# -*-coding:Latin-1 -*
import sqlite3
from Tkinter import*
import ttk
from ttk import *
#from Tkinter import Tk
import tkMessageBox   
import tkFont
#================
# attention aprrendre 
#import webbrowser
#webbrowser.open_new(r'file:///C:/Users/jamal/Desktop/Py_Doc_BD_Sujet/2_2 Fonctionnement du diagnostic dans le reseau.pdf')
#================
#---------- nous allons maintenant créer le cadre principal de l'application.
root = Tk()
root.title("Python")
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
width = 900
height = 500
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
root.geometry('%dx%d+%d+%d' % (width, height, x, y))
root.resizable(0, 0)
root.config(bg="#88ff88")

#==================================creation du base de données ============================================

def Database():
    global conn, cursor
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS 'code_erreur' (Id_error INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Erroe_Code TEXT, Level text, Signification TEXT)")
#==================================Ceci permet au code d’envoyer les données à la base de données lorsque vous cliquez sur le bouton Créer. ============================================

def Create():
    if ERRORE_CODE.get() == "" or LEVEL.get() == "" or SIGNIFICATION.get() == "" :
        txt_result.config(text="Please complete the required field!", foreground="red")
    else:
        Database()
        cursor.execute("INSERT INTO 'code_erreur' (Erroe_Code, Level, Signification) VALUES(?, ?, ?)", (str(ERRORE_CODE.get()), str(LEVEL.get()), str(SIGNIFICATION.get())))
        tree.delete(*tree.get_children())
        cursor.execute("SELECT * FROM 'code_erreur' ORDER BY 'Erroe_Code' ASC")
        fetch = cursor.fetchall()
        for data in fetch:
            tree.insert('', 'end', values=(data[0], data[1], data[2], data[3]))
        conn.commit()
        ERRORE_CODE.set("")
        LEVEL.set("")
        SIGNIFICATION.set("")
        cursor.close()
        conn.close()
        txt_result.config(text="Created a data!", foreground="green")

#=================== pour lire les données/ Ceci permet au code d'extraire les données de la base de données et de les afficher dans le widget Python appelé Treeview .==================
def Read():
    tree.delete(*tree.get_children())
    Database()
    cursor.execute("SELECT * FROM 'code_erreur' ORDER BY 'Erroe_Code' ASC")
    fetch = cursor.fetchall()
    for data in fetch:
        tree.insert('', 'end', values=(data[0], data[1], data[2], data[3]))
    cursor.close()
    conn.close()
    txt_result.config(text="Successfully read the data from database", foreground="green")


#============= PourAjouter les données pour la bdd==============
def Update():
    Database()
    if ERRORE_CODE.get() == "":
        txt_result.config(text="Please select a Erroe_Code", foreground="red")
    else:
        tree.delete(*tree.get_children())
        cursor.execute("UPDATE 'code_erreur' SET `Erroe_Code` = ?, `Level` = ?, `Signification` =? WHERE `Id_error` = ?", (str(ERRORE_CODE.get()), str(LEVEL.get()), str(SIGNIFICATION.get()), int(Id_error)))
        conn.commit()
        cursor.execute("SELECT * FROM `code_erreur` ORDER BY `Erroe_Code` ASC")
        fetch = cursor.fetchall()
        for data in fetch:
            tree.insert('', 'end', values=(data[0], data[1], data[2], data[3]))
        cursor.close()
        conn.close()
        ERRORE_CODE.set("")
        LEVEL.set("")
        SIGNIFICATION.set("")
        btn_create.config(state=NORMAL)
        btn_read.config(state=NORMAL)
        btn_update.config(state=DISABLED)
        btn_delete.config(state=NORMAL)
        txt_result.config(text="Successfully updated the data", foreground="black")

#===================

def OnSelected(event):
    global Id_error;
    curItem = tree.focus()
    contents =(tree.item(curItem))
    selecteditem = contents['values']

    Id_error = selecteditem[0]
    ERRORE_CODE.set("")
    LEVEL.set("")
    SIGNIFICATION.set("")
    
    ERRORE_CODE.set(selecteditem[1])
    LEVEL.set(selecteditem[2])
    SIGNIFICATION.set(selecteditem[3])
    
    btn_create.config(state=DISABLED)
    btn_read.config(state=DISABLED)
    btn_update.config(state=NORMAL)
    btn_delete.config(state=DISABLED)

#============= Pour supprimer les données pour la bdd==============

def Delete():
    if not tree.selection():
       txt_result.config(text="Please select an item first", foreground="red")
    else:
        result = tkMessageBox.askquestion('Python', 'Are you sure you want to delete this record?', icon="warning")
        if result == 'yes':
            curItem = tree.focus()
            contents =(tree.item(curItem))
            selecteditem = contents['values']
            tree.delete(curItem)
            Database()
            cursor.execute("DELETE FROM `code_erreur` WHERE `Id_error` = %d" % selecteditem[0])
            conn.commit()
            cursor.close()
            conn.close()
            txt_result.config(text="Successfully deleted the data", foreground="black")
#============= Pour exit l'app==============
def Exit():
    result = tkMessageBox.askquestion('Python', 'Are you sure you want to exit?', icon="warning")
    if result == 'yes':
        root.destroy()
        exit()
#==================================VARIABLES==========================================
ERRORE_CODE = StringVar()
LEVEL = StringVar()
SIGNIFICATION = StringVar()

#==================================FRAME==============================================
Top = Frame(root, width=900, height=50, border=8, relief="raise")
Top.pack(side=TOP)
Left = Frame(root, width=300, height=500, border=8, relief="raise")
Left.pack(side=LEFT)
Right = Frame(root, width=600, height=500, border=8, relief="raise")
Right.pack(side=RIGHT)
Forms = Frame(Left, width=300, height=450)
Forms.pack(side=TOP)
Buttons = Frame(Left, width=300, height=100, border=8, relief="raise")
Buttons.pack(side=BOTTOM)
RadioGroup = Frame(Forms)
#==================================LABEL WIDGET=======================================
txt_title = Label(Top, width=900, font=('arial', 24), text = "Python")
txt_title.pack()
txt_Erroe_Code = Label(Forms, text="Error_Code:", border=15)
txt_Erroe_Code.grid(row=0, sticky="e")
txt_Level = Label(Forms, text="level:" , border=15)
txt_Level.grid(row=1, sticky="e")
txt_Signification = Label(Forms, text="signification:" , border=15)
txt_Signification.grid(row=2, sticky="e")
txt_result = Label(Buttons)
txt_result.pack(side=TOP)

#==================================ENTRY WIDGET=======================================
Erroe_Code = Entry(Forms, textvariable=ERRORE_CODE, width=30)
Erroe_Code.grid(row=0, column=1)
Level = Entry(Forms, textvariable=LEVEL, width=30)
Level.grid(row=1, column=1)
RadioGroup.grid(row=2, column=1)
Signification = Entry(Forms, textvariable=SIGNIFICATION, width=30)
Signification.grid(row=2, column=1)
#==================================BUTTONS WIDGET=====================================
btn_create = Button(Buttons, width=10, text="Create", command=Create)
btn_create.pack(side=LEFT)
btn_read = Button(Buttons, width=10, text="Read", command=Read )
btn_read.pack(side=LEFT)
btn_update = Button(Buttons, width=10, text="Update", command=Update, state=DISABLED)
btn_update.pack(side=LEFT)
btn_delete = Button(Buttons, width=10, text="Delete", command=Delete)
btn_delete.pack(side=LEFT)
btn_exit = Button(Buttons, width=10, text="Exit", command=Exit)
btn_exit.pack(side=LEFT)
#==================================LIST WIDGET========================================

scrollbary = Scrollbar(Right, orient=VERTICAL)
scrollbarx = Scrollbar(Right, orient=HORIZONTAL)
tree =Treeview(Right, columns=("ID_Error", "Error_Code", "level", "signification"), selectmode="extended", height=500, 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('ID_Error', text="ID_Error", anchor=W)
tree.heading('Error_Code', text="Error_Code", anchor=W)
tree.heading('level', text="level", anchor=W)
tree.heading('signification', text="signification", anchor=W)
tree.column('#0', stretch=NO, minwidth=0, width=0)
tree.column('#1', stretch=NO, minwidth=0, width=0)
tree.column('#2', stretch=NO, minwidth=0, width=80)
tree.column('#3', stretch=NO, minwidth=0, width=50)
tree.column('#4', stretch=NO, minwidth=0, width=400)
tree.pack()
tree.bind('<Double-Button-1>', OnSelected)


#==================================INITIALIZATION=====================================
if __name__ == '__main__':

    root.mainloop()
Afficher la suite