Exemple #1
0
    def test_dateentry_allow_empty(self):
        widget = DateEntry(self.window, allow_empty=True)
        widget.pack()
        self.window.update()

        self.assertTrue(widget._allow_empty)
        self.assertEqual(widget.get(), '')  # should start with no value
        widget.focus_set()
        self.window.focus_set()
        self.assertEqual(widget.get(), '')  # should not populate with a value
        
        self.assertRaises(IndexError, widget.get_date)
        self.assertRaises(ValueError, widget.set_date, '')
Exemple #2
0
class mainWindow:
    def __init__(self, window):
        self.window = window
        self.labelFrame = tk.Frame(window, width=330, height=50)
        self.labelFrame.pack_propagate(0)
        self.header = tk.Label(self.labelFrame,
                               text='CDAC1',
                               fg='#777777',
                               font=("Impact", 26),
                               anchor=tk.NW)
        self.header.pack()
        self.labelFrame.pack(side=tk.TOP, fill=tk.X)

        # mainFrame divided in 2 parts for video capture and graph
        self.mainFrame = tk.Frame(window,
                                  height=500,
                                  width=self.window.winfo_width())
        self.mainFrame.pack_propagate(0)
        # self.mainFrame.bind("<Configure>", self.configure)

        self.imageNb = ttk.Notebook(self.mainFrame, width=600, height=500)

        #tab1 for cam1
        self.VideoFrame1 = tk.Frame(self.imageNb, width=600, height=500)
        # self.imageFrame.pack_propagate(0)
        self.imageNb.add(self.VideoFrame1, text="Cam1")

        #tab2 for cam2
        self.VideoFrame2 = tk.Frame(self.imageNb, width=600, height=500)
        self.imageNb.add(self.VideoFrame2, text="Cam2")

        #tab2 for cam2
        self.VideoFrame3 = tk.Frame(self.imageNb, width=600, height=500)
        self.imageNb.add(self.VideoFrame3, text="Cam3")

        #tab2 for cam2
        self.VideoFrame4 = tk.Frame(self.imageNb, width=600, height=500)
        self.imageNb.add(self.VideoFrame4, text="Cam4")

        #4 canvases for 4 tabs ,each canvas is placed inside the respective frame

        self.Canvas1 = tk.Canvas(self.VideoFrame1, width=600, height=500)
        self.Canvas2 = tk.Canvas(self.VideoFrame2, width=600, height=500)
        self.Canvas3 = tk.Canvas(self.VideoFrame3, width=600, height=500)
        self.Canvas4 = tk.Canvas(self.VideoFrame4, width=600, height=500)

        #pack the canvas inside the frame
        self.Canvas1.pack(fill="both", expand=1)
        self.Canvas2.pack(fill="both", expand=1)
        self.Canvas3.pack(fill="both", expand=1)
        self.Canvas4.pack(fill="both", expand=1)

        # self.imageNb.pack(expand=1, fill='y')
        self.imageNb.grid(row=0, column=0)
        self.imageNb.bind("<<NotebookTabChanged>>", self.tabchanged)
        self.mainFrame.pack(fill=tk.BOTH, side=tk.TOP)

        #Graph part
        # Frame2 shows graph and is divided in two tabs
        self.Frame2 = ttk.Notebook(self.mainFrame)
        self.graphFrame2 = ttk.Frame(self.Frame2)
        self.Frame2.add(self.graphFrame2, text="Statistics")
        self.graphFrame1 = ttk.Frame(self.Frame2)
        self.Frame2.add(self.graphFrame1, text="Custom input")

        self.InputFrame1 = ttk.Frame(self.graphFrame1, width=300, height=100)
        self.InputFrame1.pack(side=tk.TOP)
        self.inputDate1 = DateEntry(self.InputFrame1,
                                    width=12,
                                    background='darkblue',
                                    foreground='white',
                                    borderwidth=2)
        self.inputDate1.grid(row=0, column=1, padx=2)
        self.inputDate1.focus_set()
        self.label1 = ttk.Label(self.InputFrame1, text="Enter date1")
        self.label1.grid(row=0, column=0)
        self.inputDate2 = DateEntry(self.InputFrame1,
                                    width=12,
                                    background='darkblue',
                                    foreground='white',
                                    borderwidth=2)
        self.inputDate2.grid(row=1, column=1, padx=2)
        self.inputDate2.focus_set()
        self.label2 = tk.Label(self.InputFrame1, text="Enter date2")
        self.label2.grid(row=1, column=0)
        self.button1 = tk.Button(self.InputFrame1, text="Show Graph")
        self.button1.grid(row=3, column=1, padx=30, pady=10)
        self.v = tk.IntVar()
        self.v.set(0)  # initializing the choice, i.e. Python
        options = ["Line Graph", "Bar Graph"]
        for val, option in enumerate(options):
            tk.Radiobutton(self.InputFrame1,
                           text=option,
                           padx=20,
                           variable=self.v,
                           value=val).grid(row=2, column=val, padx=30)

        self.fig = plt.figure(1, figsize=(10, 8), dpi=55)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.graphFrame1)
        self.InputFrame2 = ttk.Frame(self.graphFrame2, width=300, height=100)
        self.InputFrame2.pack(side=tk.TOP)
        self.inputDate3 = DateEntry(self.InputFrame2,
                                    width=12,
                                    background='darkblue',
                                    foreground='white',
                                    borderwidth=2)
        self.inputDate3.grid(row=0, column=1, padx=2)
        self.label3 = ttk.Label(self.InputFrame2, text="Enter date")
        self.label3.grid(row=0, column=0)
        self.button2 = tk.Button(self.InputFrame2, text="Show Graph")
        self.button2.grid(row=4, column=1, padx=30, pady=10)
        self.v1 = tk.IntVar()
        self.v1.set(0)
        options1 = ["Line Graph", "Bar Graph"]
        for val, option in enumerate(options1):
            tk.Radiobutton(self.InputFrame2,
                           text=option,
                           padx=20,
                           variable=self.v1,
                           value=val).grid(row=2, column=val, padx=30)
        self.v2 = tk.IntVar()
        self.v2.set(0)
        options2 = ["Daily", "Weekly", "Monthly"]
        for val, option in enumerate(options2):
            tk.Radiobutton(self.InputFrame2,
                           text=option,
                           padx=20,
                           variable=self.v2,
                           value=val).grid(row=3, column=val, padx=10)

        self.fig1 = plt.figure(2, figsize=(10, 8), dpi=55)
        self.canvas5 = FigureCanvasTkAgg(self.fig1, master=self.graphFrame2)

        #uncomment below code for ip cameras
        # make four video captures by getting urls from database
        # linkarray = database.getVideoLinks()
        # print(linkarray)
        # self.link_arr = linkarray
        self.cap0 = cv2.VideoCapture(0)
        self.cap1 = cv2.VideoCapture(0)
        self.cap2 = cv2.VideoCapture(0)
        self.cap3 = cv2.VideoCapture(0)

        # 4 connectors for 4 different databases
        self.d1 = database.db("cam1")
        self.d2 = database.db("cam2")
        self.d3 = database.db("cam3")
        self.d4 = database.db("cam4")

        # Progress Bar and refresh button for showing disk space
        self.progressLabel = tk.Label(window, text="Used Space")
        self.progressLabel.pack()
        self.freeSpaceBar = Progressbar(window,
                                        orient=tk.HORIZONTAL,
                                        length=100,
                                        mode='determinate')
        self.freeSpaceBar.pack()
        self.refreshButton = tk.Button(window, text="Refresh")
        self.refreshButton.pack()
        self.refreshButton.bind("<Button-1>", self.findSpace)
        self.afterId = 0

        # self.showLiveAll()

    def findSpace(self, event):
        total, used, free = shutil.disk_usage("/")
        self.freeSpaceBar['value'] = (used / total) * 100

    # Function is used to display the default data for the current date
    def func(self, obj):
        self.Frame2.grid(row=0, column=1)
        self.fig.clf()
        plt.figure(1)
        y = obj.currentdata()
        if self.v.get() == 0:
            plt.plot(np.array(y)[:, 1], np.array(y)[:, 0], color='blue')
        else:
            plt.bar(np.array(y)[:, 1],
                    np.array(y)[:, 0],
                    color='blue',
                    width=.5)
        plt.xticks(rotation=45)
        plt.title("Hourly Count", fontsize=10)
        plt.ylabel("No of people", fontsize=10)
        plt.xlabel("Hour", fontsize=10)
        self.canvas.get_tk_widget().pack(expand=True,
                                         fill=tk.BOTH,
                                         side=tk.TOP)
        # self.canvas.get_tk_widget().grid(row=0, column=0)

        self.canvas.draw()
        self.fig1.clf()
        plt.figure(2)
        if self.v1.get() == 0:
            plt.plot(np.array(y)[:, 1], np.array(y)[:, 0], color='blue')
        else:
            plt.bar(np.array(y)[:, 1],
                    np.array(y)[:, 0],
                    color='blue',
                    width=.5)
        plt.xticks(rotation=45)
        plt.title("Hourly Count", fontsize=10)
        plt.ylabel("No of people", fontsize=10)
        plt.xlabel("Hour", fontsize=10)
        self.canvas5.get_tk_widget().pack(expand=True,
                                          fill=tk.BOTH,
                                          side=tk.TOP)
        self.canvas5.draw()

    # Used to display video capture for camera1
    def Enlarge1(self):
        try:

            _, frame = self.cap0.read()
            # frame = cv2.flip(frame, 1)
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            self.photo = ImageTk.PhotoImage(
                image=Image.fromarray(frame).resize((600, 500)))
            self.Canvas1.create_image(0, 0, image=self.photo, anchor=tk.NW)
            self.Canvas1.create_line(0, 300, 700, 300, fill="green")
            self.Canvas1.create_text(500, 400, text="Apoorv", fill="red")
            self.afterId = self.imageNb.after(15, self.Enlarge1)
        except:
            # self.cap0 = cv2.VideoCapture(self.link_arr[0])
            self.cap0 = cv2.VideoCapture(0)
            self.afterId = self.imageNb.after(
                15, self.Enlarge1
            )  #collects the id thats required to stop the execution of this function
            #function is stopped and started in self.tabchanged ()

    # Used to display video capture for camera2
    def Enlarge2(self):
        try:

            _, frame = self.cap1.read()
            # frame = cv2.flip(frame, 1)
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            self.photo = ImageTk.PhotoImage(
                image=Image.fromarray(frame).resize((600, 500)))
            self.Canvas2.create_image(0, 0, image=self.photo, anchor=tk.NW)
            self.Canvas2.create_line(0, 300, 700, 300, fill="green")
            self.Canvas2.create_text(500, 400, text="Apoorv", fill="red")
            self.afterId = self.imageNb.after(15, self.Enlarge2)
        except:
            # self.cap1 = cv2.VideoCapture(self.link_arr[1])
            self.cap1 = cv2.VideoCapture(0)

            self.afterId = self.imageNb.after(15, self.Enlarge2)

    # Used to display video capture for camera3
    def Enlarge3(self):
        try:
            _, frame = self.cap2.read()
            # frame = cv2.flip(frame, 1)
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            self.photo = ImageTk.PhotoImage(
                image=Image.fromarray(frame).resize((600, 500)))
            self.Canvas3.create_image(0, 0, image=self.photo, anchor=tk.NW)
            self.Canvas3.create_line(0, 300, 700, 300, fill="green")
            self.Canvas3.create_text(500, 400, text="Apoorv", fill="red")
            self.afterId = self.imageNb.after(15, self.Enlarge3)
        except:
            # self.cap2 = cv2.VideoCapture(self.link_arr[2])
            self.cap2 = cv2.VideoCapture(0)

            self.afterId = self.imageNb.after(15, self.Enlarge3)

    # Used to display video capture for camera4
    def Enlarge4(self):
        try:

            _, frame = self.cap3.read()
            # frame = cv2.flip(frame, 1)
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            self.photo = ImageTk.PhotoImage(
                image=Image.fromarray(frame).resize((600, 500)))
            self.Canvas4.create_image(0, 0, image=self.photo, anchor=tk.NW)
            self.Canvas4.create_line(0, 300, 700, 300, fill="green")
            self.Canvas4.create_text(500, 400, text="Apoorv", fill="red")
            self.afterId = self.imageNb.after(15, self.Enlarge4)
        except:
            # self.cap3 = cv2.VideoCapture(self.link_arr[2])
            self.cap3 = cv2.VideoCapture(0)

            self.afterId = self.imageNb.after(15, self.Enlarge4)

    # Used to display video capture for all cameras
    # def get_multiple_stream(cap):
    #     print("here")
    #     return cap.read()

    def tabchanged(self, event):
        if event.widget.index("current") == 0:
            try:

                self.imageNb.after_cancel(
                    self.afterId
                )  #stops the previously running enlarge function on the notebook
                print("cam1")
                self.func(self.d1)
                self.button1.bind(
                    "<Button-1>",
                    lambda event, ob1=self.d1: self.plot(event, ob1))
                self.button2.bind(
                    "<Button-1>",
                    lambda event, ob1=self.d1: self.plot1(event, ob1))
                self.Enlarge1()
            except:

                self.func(self.d1)
                self.button1.bind(
                    "<Button-1>",
                    lambda event, ob1=self.d1: self.plot(event, ob1))
                self.button2.bind(
                    "<Button-1>",
                    lambda event, ob1=self.d1: self.plot1(event, ob1))
                print("cam1")
                self.Enlarge1()
        elif event.widget.index("current") == 1:
            try:

                self.imageNb.after_cancel(self.afterId)
                print("cam2")
                #to show graphs in Frame2
                self.func(self.d2)
                self.button1.bind(
                    "<Button-1>",
                    lambda event, obj=self.d2: self.plot(event, obj))
                self.button2.bind(
                    "<Button-1>",
                    lambda event, obj=self.d2: self.plot1(event, obj))
                #to show video
                self.Enlarge2()
            except:
                self.func(self.d2)
                self.button1.bind(
                    "<Button-1>",
                    lambda event, obj=self.d2: self.plot(event, obj))
                self.button2.bind(
                    "<Button-1>",
                    lambda event, obj=self.d2: self.plot1(event, obj))
                print("cam2")
                self.Enlarge2()
        elif event.widget.index("current") == 2:
            try:
                self.func(self.d3)
                self.button1.bind(
                    "<Button-1>",
                    lambda event, obj=self.d3: self.plot(event, obj))
                self.button2.bind(
                    "<Button-1>",
                    lambda event, obj=self.d3: self.plot1(event, obj))
                self.imageNb.after_cancel(self.afterId)
                print("cam3")
                self.Enlarge3()
            except:
                self.func(self.d3)
                self.button1.bind(
                    "<Button-1>",
                    lambda event, obj=self.d3: self.plot(event, obj))
                self.button2.bind(
                    "<Button-1>",
                    lambda event, obj=self.d3: self.plot1(event, obj))
                print("cam3")
                self.Enlarge3()
        else:
            try:
                self.func(self.d4)
                self.button1.bind(
                    "<Button-1>",
                    lambda event, obj=self.d4: self.plot(event, obj))
                self.button2.bind(
                    "<Button-1>",
                    lambda event, obj=self.d4: self.plot1(event, obj))
                self.imageNb.after_cancel(self.afterId)
                print("cam1")
                self.Enlarge4()
            except:
                self.func(self.d4)
                self.button1.bind(
                    "<Button-1>",
                    lambda event, obj=self.d4: self.plot(event, obj))
                self.button2.bind(
                    "<Button-1>",
                    lambda event, obj=self.d4: self.plot1(event, obj))
                print("cam4")
                self.Enlarge4()

    # Used to disappear video capture if width decreases below a threshold

    # Function used to plot graph for custom inputs
    def plot(self, event, obj):
        plt.figure(1)
        self.fig.clf()
        inputDateStr1 = str(self.inputDate1.get_date())
        inputDateStr2 = str(self.inputDate2.get_date())
        inputDateStr1 = inputDateStr1 + ' 00:00:00'
        inputDateStr2 = inputDateStr2 + ' 00:00:00'
        date1 = datetime.strptime(inputDateStr1, "%Y-%m-%d %H:%M:%S")
        date2 = datetime.strptime(inputDateStr2, "%Y-%m-%d %H:%M:%S")
        delta = date2 - date1
        interval1 = timedelta(days=1)
        interval2 = timedelta(days=365 / 12)

        if delta < interval1:
            inputDateStr1 = "'" + inputDateStr1 + "'"
            inputDateStr2 = "'" + inputDateStr2 + "'"
            y = obj.hourlyCount(inputDateStr1, inputDateStr2)
            if self.v.get() == 0:
                plt.plot(np.array(y)[:, 1], np.array(y)[:, 0], color='blue')
            else:
                plt.bar(np.array(y)[:, 1],
                        np.array(y)[:, 0],
                        color='blue',
                        width=.5)
            plt.xticks(rotation=45)
            plt.title("Daily Count", fontsize=10)
            plt.ylabel("No of people", fontsize=10)
            plt.xlabel("Hours", fontsize=10)
            self.canvas.draw()
        elif delta < interval2:
            inputDateStr1 = "'" + inputDateStr1 + "'"
            inputDateStr2 = "'" + inputDateStr2 + "'"
            y = obj.weeklyCount(inputDateStr1, inputDateStr2)
            if self.v.get() == 0:
                plt.plot(np.array(y)[:, 1], np.array(y)[:, 0], color='blue')
            else:
                plt.bar(np.array(y)[:, 1],
                        np.array(y)[:, 0],
                        color='blue',
                        width=.5)
            plt.xticks(rotation=45)
            plt.title("Daily Count", fontsize=10)
            plt.ylabel("No of people", fontsize=10)
            plt.xlabel("Date", fontsize=10)
            self.canvas.draw()
        else:
            inputDateStr1 = "'" + inputDateStr1 + "'"
            inputDateStr2 = "'" + inputDateStr2 + "'"
            y = obj.monthlyCount(inputDateStr1, inputDateStr2)
            if self.v.get() == 0:
                plt.plot(np.array(y)[:, 1], np.array(y)[:, 0], color='blue')
            else:
                plt.bar(np.array(y)[:, 1],
                        np.array(y)[:, 0],
                        color='blue',
                        width=.5)
            plt.xticks(rotation=45)
            plt.title("Daily Count", fontsize=10)
            plt.ylabel("No of people", fontsize=10)
            plt.xlabel("Month", fontsize=10)
            self.canvas.draw()

    def plot1(self, event, obj):
        plt.figure(2)
        self.fig1.clf()
        inputDateStr1 = str(self.inputDate3.get_date())
        inputDateStr1 = inputDateStr1 + ' 00:00:00'

        if self.v2.get() == 0:
            inputDateStr1 = "'" + inputDateStr1 + "'"
            y = obj.hourlyCount(inputDateStr1, inputDateStr1)
            if self.v1.get() == 0:
                plt.plot(np.array(y)[:, 1], np.array(y)[:, 0], color='blue')
            else:
                plt.bar(np.array(y)[:, 1],
                        np.array(y)[:, 0],
                        color='blue',
                        width=.5)
            plt.xticks(rotation=45)
            plt.title("Daily Count", fontsize=10)
            plt.ylabel("No of people", fontsize=10)
            plt.xlabel("Hours", fontsize=10)
            self.canvas5.draw()
        elif self.v2.get() == 1:
            inputDateStr1 = "'" + inputDateStr1 + "'"
            y = obj.weekdata(inputDateStr1)
            if self.v1.get() == 0:
                plt.plot(np.array(y)[:, 1], np.array(y)[:, 0], color='blue')
            else:
                plt.bar(np.array(y)[:, 1],
                        np.array(y)[:, 0],
                        color='blue',
                        width=.5)
            plt.xticks(rotation=45)
            plt.title("Daily Count", fontsize=10)
            plt.ylabel("No of people", fontsize=10)
            plt.xlabel("Date", fontsize=10)
            self.canvas5.draw()
        else:
            inputDateStr1 = "'" + inputDateStr1 + "'"
            y = obj.monthdata(inputDateStr1)
            if self.v1.get() == 0:
                plt.plot(np.array(y)[:, 1], np.array(y)[:, 0], color='blue')
            else:
                plt.bar(np.array(y)[:, 1],
                        np.array(y)[:, 0],
                        color='blue',
                        width=.5)
            plt.xticks(rotation=45)
            plt.title("Daily Count", fontsize=10)
            plt.ylabel("No of people", fontsize=10)
            plt.xlabel("Month", fontsize=10)
            self.canvas5.draw()
Exemple #3
0
class StudentApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Student Management System")
        self.geometry("800x750")
        self.resizable(0, 0)
        self.Title = tk.Label(self,
                              text="سیستم مدیریت دانشجویی",
                              font=("Helvetica", 16),
                              fg="green")
        self.FName = tk.Label(self,
                              text="نام:",
                              font=("Helvetica", 10),
                              bg="white",
                              fg="black")
        self.LName = tk.Label(self,
                              text="نام خانوادگی:",
                              font=("Helvetica", 10),
                              bg="white",
                              fg="black")
        self.UnitId = tk.Label(self,
                               text="کد ملی:",
                               font=("Helvetica", 10),
                               bg="white",
                               fg="black")
        self.ContactNo = tk.Label(self,
                                  text="شماره تماس:",
                                  font=("Helvetica", 10),
                                  bg="white",
                                  fg="black")
        self.City = tk.Label(self,
                             text="شهر:",
                             font=("Helvetica", 10),
                             bg="white",
                             fg="black")
        self.State = tk.Label(self,
                              text="استان:",
                              font=("Helvetica", 10),
                              bg="white",
                              fg="black")
        self.DOB = tk.Label(self,
                            text="تاریخ تولد:",
                            font=("Helvetica", 10),
                            bg="white",
                            fg="black")
        self.Select = tk.Label(
            self,
            text=
            "لطفا یکی از رکورد های زیر را برای آپدیت یا پاک کردن انتخاب کنید",
            font=("Helvetica", 10),
            bg="white",
            fg="black")
        self.Search = tk.Label(self,
                               text="لطفا شماره ردیف را وارد کنید:",
                               font=("Helvetica", 10),
                               bg="white",
                               fg="black")
        # Create Entry for Input Data
        self.entFName = tk.Entry(self)
        self.entLName = tk.Entry(self)
        self.entUnit = tk.Entry(self)
        self.entContact = tk.Entry(self)
        self.entCity = tk.Entry(self)
        self.entState = tk.Entry(self)
        self.calDOB = DateEntry(self,
                                width=12,
                                background='darkblue',
                                foreground='white',
                                borderwidth=2,
                                year=1950,
                                locale='en_US',
                                date_pattern='y-mm-dd')
        # self.entDOB = tk.Entry(self)
        self.entSearch = tk.Entry(self)

        # Create Button for Submit or ... Data's
        self.btn_register = tk.Button(self,
                                      text="ثبت",
                                      font=("Helvetica", 11),
                                      bg="green",
                                      fg="black",
                                      command=self.register_student)
        self.btn_update = tk.Button(self,
                                    text="آپدیت",
                                    font=("Helvetica", 11),
                                    bg="lightgreen",
                                    fg="black",
                                    command=self.update_student_data)
        self.btn_delete = tk.Button(self,
                                    text="پاک کردن",
                                    font=("Helvetica", 11),
                                    bg="yellow",
                                    fg="black",
                                    command=self.delete_student_data)
        self.btn_clear = tk.Button(self,
                                   text="دیلیت رکورد",
                                   font=("Helvetica", 11),
                                   bg="red",
                                   fg="black",
                                   command=self.clear_form)
        self.btn_show_all = tk.Button(self,
                                      text="نمایش همه",
                                      font=("Helvetica", 11),
                                      bg="blue",
                                      fg="black",
                                      command=self.load_student_data)
        self.btn_search = tk.Button(self,
                                    text="جست و جو",
                                    font=("Helvetica", 11),
                                    bg="lightblue",
                                    fg="black",
                                    command=self.show_search_record)
        self.btn_exit = tk.Button(self,
                                  text="خروج",
                                  font=("Helvetica", 16),
                                  bg="brown",
                                  fg="white",
                                  command=self.exit)
        # Title of Table Show Student's Data
        columns = ("#1", "#2", "#3", "#4", "#5", "#6", "#7", "#8")
        self.tvStudent = ttk.Treeview(self,
                                      show="headings",
                                      height="5",
                                      columns=columns)
        self.tvStudent.heading('#1', text='شماره ردیف', anchor='center')
        self.tvStudent.column('#1', width=80, anchor='center', stretch=False)
        self.tvStudent.heading('#2', text='نام', anchor='center')
        self.tvStudent.column('#2', width=10, anchor='center', stretch=True)
        self.tvStudent.heading('#3', text='نام خانوادگی', anchor='center')
        self.tvStudent.column('#3', width=10, anchor='center', stretch=True)
        self.tvStudent.heading('#4', text='کد ملی', anchor='center')
        self.tvStudent.column('#4', width=10, anchor='center', stretch=True)
        self.tvStudent.heading('#5', text='شهر', anchor='center')
        self.tvStudent.column('#5', width=10, anchor='center', stretch=True)
        self.tvStudent.heading('#6', text='استان', anchor='center')
        self.tvStudent.column('#6', width=10, anchor='center', stretch=True)
        self.tvStudent.heading('#7', text='شماره تماس', anchor='center')
        self.tvStudent.column('#7', width=10, anchor='center', stretch=True)
        self.tvStudent.heading('#8', text='تاریخ تولد', anchor='center')
        self.tvStudent.column('#8', width=10, anchor='center', stretch=True)

        # Scroll bars are set up below considering placement position(x&y) ,height and width of treeview widget
        vsb = ttk.Scrollbar(self,
                            orient=tk.VERTICAL,
                            command=self.tvStudent.yview)
        vsb.place(x=40 + 640 + 1, y=310, height=180 + 20)
        self.tvStudent.configure(yscroll=vsb.set)
        hsb = ttk.Scrollbar(self,
                            orient=tk.HORIZONTAL,
                            command=self.tvStudent.xview)
        hsb.place(x=40, y=310 + 200 + 1, width=620 + 20)
        self.tvStudent.configure(xscroll=hsb.set)
        self.tvStudent.bind("<<TreeviewSelect>>", self.show_selected_record)
        # Create A plase of label's
        self.Title.place(x=250, y=10, height=27, width=300)
        self.FName.place(x=206, y=40, height=23, width=100)
        self.LName.place(x=207, y=70, height=23, width=100)
        self.UnitId.place(x=203, y=100, height=23, width=104)
        self.ContactNo.place(x=203, y=130, height=23, width=104)
        self.City.place(x=242, y=160, height=23, width=65)
        self.State.place(x=236, y=190, height=23, width=71)
        self.DOB.place(x=180, y=220, height=23, width=128)
        self.Select.place(x=197, y=280, height=23, width=400)
        self.Search.place(x=170, y=560, height=23, width=134)
        # Create A plase of Entry's
        self.entFName.place(x=330, y=40, height=21, width=186)
        self.entLName.place(x=330, y=70, height=21, width=186)
        self.entUnit.place(x=330, y=100, height=21, width=186)
        self.entContact.place(x=330, y=130, height=21, width=186)
        self.entCity.place(x=330, y=160, height=21, width=186)
        self.entState.place(x=330, y=190, height=21, width=186)
        self.calDOB.place(x=330, y=220, height=21, width=186)
        # Create A plase of Buttons's
        self.entSearch.place(x=310, y=560, height=21, width=186)
        self.btn_register.place(x=200, y=245, height=25, width=76)
        self.btn_update.place(x=280, y=245, height=25, width=76)
        self.btn_delete.place(x=360, y=245, height=25, width=76)
        self.btn_clear.place(x=440, y=245, height=25, width=76)
        self.btn_show_all.place(x=520, y=245, height=25, width=76)
        self.btn_search.place(x=505, y=558, height=26, width=60)
        self.btn_exit.place(x=720, y=610, height=31, width=60)
        self.tvStudent.place(x=80, y=310, height=200, width=600)
        # Create Table & load Student Data
        self.create_table()
        self.load_student_data()

    # clear Form's
    def clear_form(self):
        self.entFName.delete(0, tk.END)
        self.entLName.delete(0, tk.END)
        self.entUnit.delete(0, tk.END)
        self.entContact.delete(0, tk.END)
        self.entCity.delete(0, tk.END)
        self.entState.delete(0, tk.END)
        self.calDOB.delete(0, tk.END)

    # Exit from Task
    def exit(self):
        MsgBox = mb.askquestion('خروج از برنامه',
                                'آیا مطمئن هستید که میخواهید خارج شوید',
                                icon='warning')
        if MsgBox == 'yes':
            self.destroy()

    # Delete Student Data From DB
    def delete_student_data(self):
        MsgBox = mb.askquestion('پاک کردن رکورد',
                                'آیا از پاک کردن رکورد مطمئن هستید؟',
                                icon='warning')
        if MsgBox == 'yes':
            if db_connection.is_connected() == False:
                db_connection.connect()
            db_cursor.execute("use Student")  # Interact with Student Database
            # deleteing selected student record
            Delete = "delete from student_master where RollNo='%s'" % (roll_no)
            db_cursor.execute(Delete)
            db_connection.commit()
            mb.showinfo("Information", "رکورد دانشجوی مورد نظر پاک شد")
            self.load_student_data()
            self.entFName.delete(0, tk.END)
            self.entLName.delete(0, tk.END)
            self.entUnit.delete(0, tk.END)
            self.entContact.delete(0, tk.END)
            self.entCity.delete(0, tk.END)
            self.entState.delete(0, tk.END)
            self.calDOB.delete(0, tk.END)

    # Create Table in DB
    def create_table(self):
        if db_connection.is_connected() == False:
            db_connection.connect()
        # executing cursor with execute method and pass SQL query
        db_cursor.execute("CREATE DATABASE IF NOT EXISTS Student"
                          )  # Create a Database Named Student
        db_cursor.execute("use Student")  # Interact with Student Database
        # creating required tables
        db_cursor.execute(
            "create table if not exists Student_master(Id INT(11) NOT NULL  PRIMARY KEY AUTO_INCREMENT,rollno INT(15),fname VARCHAR(30),lname VARCHAR(30),meli VARCHAR(11), city VARCHAR(20),state VARCHAR(30),mobileno VARCHAR(11),dob date)AUTO_INCREMENT=1"
        )
        db_connection.commit()

    # Add Student To Data Base
    def register_student(self):
        if db_connection.is_connected() == False:
            db_connection.connect()
        fname = self.entFName.get()  # Retrieving entered first name
        lname = self.entLName.get()  # Retrieving entered last name
        unit_id = self.entUnit.get()  # # Retrieving entered code number
        contact_no = self.entContact.get()  # Retrieving entered contact number
        city = self.entCity.get()  # Retrieving entered city name
        state = self.entState.get()  # Retrieving entered state name
        dob = self.calDOB.get()  # Retrieving choosen date
        # validating Entry Widgets
        if fname == "":
            mb.showinfo('Information', "لطفا نام را وارد کنید")
            self.entFName.focus_set()
            return
        if lname == "":
            mb.showinfo('Information', "لطفا نام خانوادگی را وارد کنید")
            self.entLName.focus_set()
            return
        if unit_id == "":
            mb.showinfo('Information', "لطفا کد ملی را وارد کنید")
            self.entUnit.focus_set()
            return
        if contact_no == "":
            mb.showinfo('Information', "لطفا شماره تماس را وارد کنید")
            self.entContact.focus_set()
            return
        if city == "":
            mb.showinfo('Information', "لطفا نام شهر را وارد کنید")
            self.entCity.focus_set()
            return
        if state == "":
            mb.showinfo('Information', "لطفا نام استان را وارد کنید")
            self.entState.focus_set()
            return
        if dob == "":
            mb.showinfo('Information', "لطفا تاریخ تولد را انتخاب کنید")
            self.calDOB.focus_set()
            return

        # Inserting record into student_master table of student database
        try:
            rollno = int(self.fetch_max_roll_no())
            print("New Student Id: " + str(rollno))
            query2 = "INSERT INTO student_master (rollno, fname,lname,city,state,meli,mobileno,dob) VALUES (%s, %s,%s,%s, %s,%s, %s, %s)"
            # implement query Sentence
            db_cursor.execute(
                query2,
                (rollno, fname, lname, city, state, unit_id, contact_no, dob))
            mb.showinfo('Information', "دانشجو با موفقیت ثبت شد")
            # Submit to database for execution
            db_connection.commit()
            self.load_student_data()
        except mysql.connector.Error as err:
            print(err)
            # Rollback in case there is any error
            db_connection.rollback()
            mb.showinfo('Information', "داده های وارد شده با خطا مواجه شد!!!")
        finally:
            db_connection.close()

    def fetch_max_roll_no(self):
        if db_connection.is_connected() == False:
            db_connection.connect()
        db_cursor.execute("use Student")  # Interact with Student Database
        rollno = 0
        query1 = "SELECT rollno FROM student_master order by  id DESC LIMIT 1"
        # implement query Sentence
        db_cursor.execute(query1)  # Retrieving maximum student id no
        print("No of Record Fetched:" + str(db_cursor.rowcount))
        if db_cursor.rowcount == 0:
            rollno = 1
        else:
            rows = db_cursor.fetchall()
            for row in rows:
                rollno = row[0]
            rollno = rollno + 1
        print("Max Student Id: " + str(rollno))
        return rollno

    # show Record From DB If Search that
    def show_search_record(self):
        if db_connection.is_connected() == False:
            db_connection.connect()
        s_roll_no = self.entSearch.get()  # Retrieving entered first name
        print(s_roll_no)
        if s_roll_no == "":
            mb.showinfo('Information', "لطفا مقداری را وارد نمایید!!!")
            self.entSearch.focus_set()
            return
        self.tvStudent.delete(
            *self.tvStudent.get_children())  # clears the treeview tvStudent
        # Inserting record into student_master table of student database
        db_cursor.execute("use Student")  # Interact with Bank Database
        sql = "SELECT rollno,fname,lname,city,state,mobileno,date_format(dob,'%d-%m-%Y') FROM student_master where rollno='" + s_roll_no + "'"
        db_cursor.execute(sql)
        total = db_cursor.rowcount
        # if total ==0:
        # mb.showinfo("Info", "Nothing To Display,Please add data")
        # return
        print("Total Data Entries:" + str(total))
        rows = db_cursor.fetchall()

        RollNo = ""
        First_Name = ""
        Last_Name = ""
        Unit_Meli = ""
        City = ""
        State = ""
        Phone_Number = ""
        DOB = ""
        for row in rows:
            RollNo = row[0]
            First_Name = row[1]
            Last_Name = row[2]
            City = row[3]
            State = row[4]
            Unit_Meli = row[5]
            Phone_Number = row[6]
            DOB = row[7]
            print(Phone_Number)
            self.tvStudent.insert("",
                                  'end',
                                  text=RollNo,
                                  values=(RollNo, First_Name, Last_Name, City,
                                          State, Unit_Meli, Phone_Number, DOB))

    # show Selection Record From DataBase
    def show_selected_record(self, event):
        self.clear_form()
        for selection in self.tvStudent.selection():
            item = self.tvStudent.item(selection)
        global roll_no
        roll_no, first_name, last_name, city, state, unit_id, contact_no, dob = item[
            "values"][0:8]
        self.entFName.insert(0, first_name)
        self.entLName.insert(0, last_name)
        self.entCity.insert(0, city)
        self.entState.insert(0, state)
        self.entUnit.insert(0, unit_id)
        self.entContact.insert(0, contact_no)
        self.calDOB.insert(0, dob)
        return roll_no

    # Update Recourd of Student in DataBase
    def update_student_data(self):
        if db_connection.is_connected() == False:
            db_connection.connect()
        print("Updating")
        db_cursor.execute("use Student")  # Interact with Student Database
        First_Name = self.entFName.get()
        Last_Name = self.entLName.get()
        Unit_Meli = self.entUnit.get()
        Phone_Number = self.entContact.get()
        City = self.entCity.get()
        State = self.entState.get()
        DOB = self.calDOB.get()
        print(roll_no)
        Update = "Update student_master set fname='%s', lname='%s', meli='%s' , mobileno='%s', city='%s', state='%s', dob='%s' where rollno='%s'" % (
            First_Name, Last_Name, Unit_Meli, Phone_Number, City, State, DOB,
            roll_no)
        db_cursor.execute(Update)
        db_connection.commit()
        mb.showinfo("Info", "رکورد دانشجوی انتخاب شده با موفقیت به روز شد")
        # show all
        self.load_student_data()

    # load Student Data From Database
    def load_student_data(self):
        if db_connection.is_connected() == False:
            db_connection.connect()
        self.calDOB.delete(0, tk.END)  # clears the date entry widget
        self.tvStudent.delete(
            *self.tvStudent.get_children())  # clears the treeview tvStudent
        # Inserting record into student_master table of student database
        db_cursor.execute("use Student")  # Interact with Bank Database
        sql = "SELECT rollno,fname,lname,city,state,meli,mobileno,date_format(dob,'%d-%m-%Y') FROM student_master"
        db_cursor.execute(sql)
        total = db_cursor.rowcount
        # if total ==0:
        # mb.showinfo("Info", "Nothing To Display,Please add data")
        # return
        print("Total Data Entries:" + str(total))
        rows = db_cursor.fetchall()

        RollNo = ""
        First_Name = ""
        Last_Name = ""
        City = ""
        State = ""
        Unit_Meli = ""
        Phone_Number = ""
        DOB = ""
        for row in rows:
            RollNo = row[0]
            First_Name = row[1]
            Last_Name = row[2]
            City = row[3]
            State = row[4]
            Unit_Meli = row = [5]
            Phone_Number = row[6]
            DOB = row[7]
            self.tvStudent.insert("",
                                  'end',
                                  text=RollNo,
                                  values=(RollNo, First_Name, Last_Name, City,
                                          State, Phone_Number, DOB))
Exemple #4
0
class DesktopApp(tk.Tk):  #root class
    def __init__(self):
        super().__init__()
        self.title("Desktops Management System")
        self.geometry(
            "840x640+640+200")  #scrn_length*scrn_breadth+scrnXpos+scrnYpos

        #LABELS
        self.lblTitle = tk.Label(self,
                                 text="Desktops Management System",
                                 font=("Helvetica", 16),
                                 bg="yellow",
                                 fg="green",
                                 relief="ridge")
        self.lblName = tk.Label(self,
                                text="UserName:"******"Helvetica", 10),
                                bg="blue",
                                fg="yellow")
        self.lblCPU = tk.Label(self,
                               text="CPU usage : ",
                               font=("Helvetica", 10),
                               bg="blue",
                               fg="yellow")
        self.lblDisk = tk.Label(self,
                                text="Disk storage : ",
                                font=("Helvetica", 10),
                                bg="blue",
                                fg="yellow")
        self.lblLocal = tk.Label(self,
                                 text="Localhost : ",
                                 font=("Helvetica", 10),
                                 bg="blue",
                                 fg="yellow")
        self.lblNet = tk.Label(self,
                               text="Network Status : ",
                               font=("Helvetica", 10),
                               bg="blue",
                               fg="yellow")
        self.lblMemo = tk.Label(self,
                                text="Memory usage : ",
                                font=("Helvetica", 10),
                                bg="blue",
                                fg="yellow")
        self.lblDate = tk.Label(self,
                                text="Select Date : ",
                                font=("Helvetica", 10),
                                bg="blue",
                                fg="yellow")
        self.lblSelect = tk.Label(
            self,
            text="Please select one record below to update or delete",
            font=("Helvetica", 10),
            bg="blue",
            fg="yellow")  #MESSAGE
        self.lblSearch = tk.Label(self,
                                  text="Please Enter System ID:",
                                  font=("Helvetica", 10),
                                  bg="blue",
                                  fg="yellow")

        #ENTRIES
        self.entName = tk.Entry(self)
        self.entCPU = tk.Entry(self)
        self.entDisk = tk.Entry(self)
        self.entLocal = tk.Entry(self)
        self.entNet = tk.Entry(self)
        self.entMemo = tk.Entry(self)
        self.entSearch = tk.Entry(self)

        self.entDate = DateEntry(self,
                                 width=12,
                                 background='darkblue',
                                 foreground='white',
                                 borderwidth=2,
                                 year=2021,
                                 locale='en_US',
                                 date_pattern='y-mm-dd')

        #BUTTONS
        self.btnRegister = tk.Button(self,
                                     text="Register",
                                     font=("Helvetica", 11),
                                     bg="yellow",
                                     fg="blue",
                                     command=self.register_desktop)
        self.btnUpdate = tk.Button(self,
                                   text="Update",
                                   font=("Helvetica", 11),
                                   bg="yellow",
                                   fg="blue",
                                   command=self.update_desktop)
        self.btnDelete = tk.Button(self,
                                   text="Delete",
                                   font=("Helvetica", 11),
                                   bg="yellow",
                                   fg="blue",
                                   command=self.delete_desktop_data)
        self.btnClear = tk.Button(self,
                                  text="Clear",
                                  font=("Helvetica", 11),
                                  bg="yellow",
                                  fg="blue",
                                  command=self.clear_form)
        self.btnShowAll = tk.Button(self,
                                    text="Show All",
                                    font=("Helvetica", 11),
                                    bg="yellow",
                                    fg="blue",
                                    command=self.load_desktop_data)
        self.btnSearch = tk.Button(self,
                                   text="Search",
                                   font=("Helvetica", 11),
                                   bg="yellow",
                                   fg="blue",
                                   command=self.show_search_record)
        self.btnExit = tk.Button(self,
                                 text="Exit",
                                 font=("Helvetica", 11),
                                 bg="yellow",
                                 fg="blue",
                                 command=self.exit)

        #TABLE(TREEVIEW)
        columns = ("#1", "#2", "#3", "#4", "#5", "#6", "#7", "#8")
        self.tvDesktop = ttk.Treeview(self,
                                      show="headings",
                                      height="50",
                                      columns=columns)
        self.tvDesktop.heading('#1', text='DeskID', anchor='center')
        self.tvDesktop.column('#1', width=10, anchor='center', stretch=True)
        self.tvDesktop.heading('#2', text='UserName', anchor='center')
        self.tvDesktop.column('#2', width=10, anchor='center', stretch=True)
        self.tvDesktop.heading('#3', text='Processor', anchor='center')
        self.tvDesktop.column('#3', width=12, anchor='center', stretch=True)
        self.tvDesktop.heading('#4', text='Storage', anchor='center')
        self.tvDesktop.column('#4', width=12, anchor='center', stretch=True)
        self.tvDesktop.heading('#5', text='Localhost', anchor='center')
        self.tvDesktop.column('#5', width=12, anchor='center', stretch=True)
        self.tvDesktop.heading('#6', text='Network', anchor='center')
        self.tvDesktop.column('#6', width=12, anchor='center', stretch=True)
        self.tvDesktop.heading('#7', text='Memory', anchor='center')
        self.tvDesktop.column('#7', width=12, anchor='center', stretch=True)
        self.tvDesktop.heading('#8', text='Date', anchor='center')
        self.tvDesktop.column('#8', width=10, anchor='center', stretch=True)

        #SCROLL BARS
        vsb = ttk.Scrollbar(self,
                            orient=tk.VERTICAL,
                            command=self.tvDesktop.yview)
        vsb.place(x=40 + 640 + 1, y=310, height=180 + 20)
        self.tvDesktop.configure(yscroll=vsb.set)
        hsb = ttk.Scrollbar(self,
                            orient=tk.HORIZONTAL,
                            command=self.tvDesktop.xview)
        hsb.place(x=40, y=310 + 200 + 1, width=620 + 20)
        self.tvDesktop.configure(xscroll=hsb.set)
        self.tvDesktop.bind("<<TreeviewSelect>>", self.show_selected_record)

        #LABELS
        self.lblTitle.place(x=270, y=27, height=30, width=300)

        self.lblName.place(x=30, y=70, height=25, width=125)
        self.lblCPU.place(x=30, y=115, height=25, width=125)
        self.lblDisk.place(x=30, y=160, height=25, width=125)

        self.lblLocal.place(x=410, y=70, height=25, width=125)
        self.lblNet.place(x=410, y=115, height=25, width=125)
        self.lblMemo.place(x=410, y=160, height=25, width=125)

        self.lblDate.place(x=30, y=205, height=25, width=125)
        self.lblSearch.place(x=30, y=560, height=25, width=225)
        self.lblSelect.place(x=166, y=290, height=20, width=436)

        #ENTRIES
        self.entName.place(x=170, y=70, height=25, width=225)
        self.entCPU.place(x=170, y=115, height=25, width=225)
        self.entDisk.place(x=170, y=160, height=25, width=225)

        self.entLocal.place(x=550, y=70, height=25, width=225)
        self.entNet.place(x=550, y=115, height=25, width=225)
        self.entMemo.place(x=550, y=160, height=25, width=225)

        self.entDate.place(x=170, y=205, height=25, width=225)
        self.entSearch.place(x=270, y=560, height=25, width=225)

        #BUTTONS
        self.btnUpdate.place(x=98, y=250, height=25, width=106)
        self.btnDelete.place(x=234, y=250, height=25, width=106)
        self.btnRegister.place(x=370, y=250, height=25, width=106)
        self.btnClear.place(x=506, y=250, height=25, width=106)
        self.btnShowAll.place(x=642, y=250, height=25, width=106)
        self.btnSearch.place(x=505, y=558, height=45, width=114)
        self.btnExit.place(x=649, y=558, height=45, width=114)

        self.tvDesktop.place(x=40, y=310, height=200, width=640)
        self.create_table()
        self.load_desktop_data()

    def clear_form(self):
        self.entName.delete(0, tk.END)
        self.entCPU.delete(0, tk.END)
        self.entDisk.delete(0, tk.END)
        self.entLocal.delete(0, tk.END)
        self.entNet.delete(0, tk.END)
        self.entMemo.delete(0, tk.END)
        self.entDate.delete(0, tk.END)

    def exit(self):
        MsgBox = mb.askquestion(
            'Exit Application',
            'Are you sure you want to exit the application?',
            icon='warning')
        if MsgBox == 'yes':
            self.destroy()

    def delete_desktop_data(self):
        MsgBox = mb.askquestion(
            'Delete Record',
            'Are you sure! you want to delete selected desktop record?',
            icon='warning')
        if MsgBox == 'yes':
            if db_connection.is_connected() == False:
                db_connection.connect()
        db_cursor.execute("USE Desktop")  # Interact with  Database
        # deleteing selected Desktop record
        Delete = "DELETE FROM Desktop_master WHERE deskno='%s'" % (Desk_Number)
        db_cursor.execute(Delete)
        db_connection.commit()
        mb.showinfo("Information", "Desktop Record Deleted Succssfully")
        self.load_desktop_data()
        self.entName.delete(0, tk.END)
        self.entCPU.delete(0, tk.END)
        self.entDisk.delete(0, tk.END)
        self.entLocal.delete(0, tk.END)
        self.entNet.delete(0, tk.END)
        self.entMemo.delete(0, tk.END)
        self.entDate.delete(0, tk.END)

    def create_table(self):
        if db_connection.is_connected() == False:
            db_connection.connect()
        # executing cursor with execute method and pass SQL query
        db_cursor.execute("CREATE DATABASE IF NOT EXISTS Desktop"
                          )  # Create a Database named Desktop
        db_cursor.execute("USE Desktop")  # Interact with Desktop Database
        # creating required tables
        db_cursor.execute(
            "CREATE TABLE IF NOT EXISTS Desktop_master(Id INT(10) NOT NULL PRIMARY KEY AUTO_INCREMENT,deskno INT(15),uname VARCHAR(30),CPU VARCHAR(30), disk VARCHAR(30), localhost VARCHAR(30),network VARCHAR(30), memory VARCHAR(30), joindate DATE)AUTO_INCREMENT=1"
        )
        db_connection.commit()

    def register_desktop(self):
        if db_connection.is_connected() == False:
            db_connection.connect()
        name_data = self.entName.get()
        CPU_data = self.entCPU.get()
        disk_data = self.entDisk.get()
        local_data = self.entLocal.get()
        network_data = self.entNet.get()
        memory_data = self.entMemo.get()
        date_data = self.entDate.get()

        #ALERT USER FOR EMPTY FIELDS
        if name_data == "":
            mb.showinfo('Information', "Please Enter Name")
            self.entName.focus_set()
            return
        if CPU_data == "":
            mb.showinfo('Information', "Please Enter CPU Stat")
            self.entCPU.focus_set()
            return
        if disk_data == "":
            mb.showinfo('Information', "Please Enter Disk Stat")
            self.entDisk.focus_set()
            return
        if local_data == "":
            mb.showinfo('Information', "Please Enter Localhost Stat")
            self.entLocal.focus_set()
            return
        if network_data == "":
            mb.showinfo('Information', "Please Enter Network Stat")
            self.entNet.focus_set()
            return
        if memory_data == "":
            mb.showinfo('Information', "Please Enter Memory Stat")
            self.entMemo.focus_set()
            return
        if date_data == "":
            mb.showinfo('Information', "Please Enter the Date")
            self.entDate.focus_set()
            return

        # Inserting record into Desktop_master table of Desktop database
        try:
            deskno = int(self.fetch_max_desk_no())
            print("New Desktop Id: " + str(deskno))
            query2 = "INSERT INTO Desktop_master (deskno, uname, CPU, disk, localhost, network, memory, joindate) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
            # implement query Sentence
            db_cursor.execute(
                query2, (deskno, name_data, CPU_data, disk_data, local_data,
                         network_data, memory_data, date_data))
            mb.showinfo('Information', "Desktop Registration Successfully")
            # Submit to database for execution
            db_connection.commit()
            self.load_desktop_data()
        except mysql.connector.Error as err:
            print(err)
            # Rollback in case there is any error
            db_connection.rollback()
            mb.showinfo('Information', "Data Insertion Failed!!!")
        finally:
            db_connection.close()

    def fetch_max_desk_no(self):
        if db_connection.is_connected() == False:
            db_connection.connect()
        db_cursor.execute("USE Desktop")  # Interact with desktop Database
        deskno = 0
        query1 = "SELECT deskno FROM Desktop_master order by  id DESC LIMIT 1"
        # implement query Sentence
        db_cursor.execute(query1)  # Retrieving maximum desktop id no
        print("No of Records Fetched:" + str(db_cursor.rowcount))
        if db_cursor.rowcount == 0:
            deskno = 1
        else:
            rows = db_cursor.fetchall()
            for row in rows:
                deskno = row[0]
            deskno = deskno + 1
        print("Max desktop Id: " + str(deskno))
        return deskno

    def show_search_record(self):
        if db_connection.is_connected() == False:
            db_connection.connect()
        s_desk_no = self.entSearch.get()
        print(s_desk_no)
        if s_desk_no == "":
            mb.showinfo('Information', "Please Enter Desktop Number")
            self.entSearch.focus_set()
            return
        self.tvDesktop.delete(*self.tvDesktop.get_children())
        db_cursor.execute("USE Desktop")
        query3 = "SELECT deskno, uname, CPU, disk, localhost, network, memory, date_format(joindate,'%d-%m-%Y') FROM Desktop_master WHERE deskno='" + s_desk_no + "'"
        db_cursor.execute(query3)
        total = db_cursor.rowcount
        print("Total Desktops : " + str(total))
        rows = db_cursor.fetchall()

        Desk_No = ""
        User_Name = ""
        CPU_Stat = ""
        disk_Stat = ""
        local_Stat = ""
        net_Stat = ""
        memo_Stat = ""
        date_Stat = ""

        for row in rows:
            Desk_No = row[0]
            User_Name = row[1]
            CPU_Stat = row[2]
            disk_Stat = row[3]
            local_Stat = row[4]
            net_Stat = row[5]
            memo_Stat = row[6]
            date_Stat = row[7]
            print("Desk Number: " + str(Desk_No))
            self.tvDesktop.insert("",
                                  'end',
                                  text=Desk_No,
                                  values=(Desk_No, User_Name, CPU_Stat,
                                          disk_Stat, local_Stat, net_Stat,
                                          memo_Stat, date_Stat))

    def show_selected_record(self, event):
        self.clear_form()
        for selection in self.tvDesktop.selection():
            item = self.tvDesktop.item(selection)
        global Desk_Number
        Desk_Number, PCname, PCcpu, PCdisk, PClocal, PCnet, PCmem, PCdate = item[
            "values"][0:8]
        self.entName.insert(0, PCname)
        self.entCPU.insert(0, PCcpu)
        self.entDisk.insert(0, PCdisk)
        self.entLocal.insert(0, PClocal)
        self.entNet.insert(0, PCnet)
        self.entMemo.insert(0, PCmem)
        self.entDate.insert(0, PCdate)
        return Desk_Number

    def update_desktop(self):
        if db_connection.is_connected() == False:
            db_connection.connect()
        print("Updating")
        db_cursor.execute("USE Desktop")
        User_Name = self.entName.get()
        CPU_Stat = self.entCPU.get()
        disk_Stat = self.entDisk.get()
        local_Stat = self.entLocal.get()
        net_Stat = self.entNet.get()
        memo_Stat = self.entMemo.get()
        date_Stat = self.entDate.get()
        print(Desk_Number)
        query4 = "UPDATE Desktop_master SET uname='%s', CPU='%s', disk='%s', localhost='%s', network='%s', memory='%s', joindate='%s' WHERE deskno='%s'" % (
            User_Name, CPU_Stat, disk_Stat, local_Stat, net_Stat, memo_Stat,
            date_Stat, Desk_Number)
        db_cursor.execute(query4)
        db_connection.commit()
        mb.showinfo("Info", "Selected Desktop Record Updated Successfully ")
        self.load_desktop_data()

    def load_desktop_data(self):
        if db_connection.is_connected() == False:
            db_connection.connect()
        self.entDate.delete(0, tk.END)
        self.tvDesktop.delete(*self.tvDesktop.get_children())
        db_cursor.execute("USE Desktop")
        query5 = "SELECT deskno, uname, CPU, disk, localhost, network, memory, date_format(joindate,'%d-%m-%Y') FROM Desktop_master"
        db_cursor.execute(query5)
        total = db_cursor.rowcount
        #if total ==0:
        #mb.showinfo("Info", "Nothing To Display,Please add data")
        #return
        print("Total Data Entries:" + str(total))
        rows = db_cursor.fetchall()

        Desk_No = ""
        User_Name = ""
        CPU_Stat = ""
        disk_Stat = ""
        local_Stat = ""
        net_Stat = ""
        memo_Stat = ""
        date_Stat = ""

        for row in rows:
            Desk_No = row[0]
            User_Name = row[1]
            CPU_Stat = row[2]
            disk_Stat = row[3]
            local_Stat = row[4]
            net_Stat = row[5]
            memo_Stat = row[6]
            date_Stat = row[7]

            self.tvDesktop.insert("",
                                  'end',
                                  text=Desk_No,
                                  values=(Desk_No, User_Name, CPU_Stat,
                                          disk_Stat, local_Stat, net_Stat,
                                          memo_Stat, date_Stat))