Open excel file in Tkinter and plot graphs Open excel file in Tkinter and plot graphs tkinter tkinter

Open excel file in Tkinter and plot graphs


In class use some self.variable to keep information and then you can use it in other methods in class.

In example I use method load() to load file and create dataframe, and method display() to display this dataframe in text widget.

try:    # Python 2    import Tkinter as tk    import ttk    from tkFileDialog import askopenfilenameexcept ImportError:    # Python 3    import tkinter as tk    from tkinter import ttk    from tkinter.filedialog import askopenfilenameimport pandas as pd# --- classes ---class MyWindow:    def __init__(self, parent):        self.parent = parent        self.filename = None        self.df = None        self.text = tk.Text(self.parent)        self.text.pack()        self.button = tk.Button(self.parent, text='LOAD DATA', command=self.load)        self.button.pack()        self.button = tk.Button(self.parent, text='DISPLAY DATA', command=self.display)        self.button.pack()    def load(self):        name = askopenfilename(filetypes=[('CSV', '*.csv',), ('Excel', ('*.xls', '*.xlsx'))])        if name:            if name.endswith('.csv'):                self.df = pd.read_csv(name)            else:                self.df = pd.read_excel(name)            self.filename = name            # display directly            #self.text.insert('end', str(self.df.head()) + '\n')    def display(self):        # ask for file if not loaded yet        if self.df is None:            self.load()        # display if loaded        if self.df is not None:            self.text.insert('end', self.filename + '\n')            self.text.insert('end', str(self.df.head()) + '\n')# --- main ---if __name__ == '__main__':    root = tk.Tk()    top = MyWindow(root)    root.mainloop()


Here i have fetch the excel data and store it in the graph, but i want my graph should plot data after 5 second,and the graph should run in the Run time.

from openpyxl import load_workbookimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec# read  from excel filewb = load_workbook('C:\\Users\\Acer-i5-607\\Desktop\\case1.xlsx')sheet_1 = wb.get_sheet_by_name('case1')plt.figure(figsize=(6, 4), facecolor='Grey')G = gridspec.GridSpec(6, 2)axes_1 = plt.subplot(G[0, :])x = np.zeros(sheet_1.max_row)y = np.zeros(len(x))for i in range(1, sheet_1.max_row):    x[i] = sheet_1.cell(row=i + 1, column=2).value    y[i] = sheet_1.cell(row=i + 1, column=4).value#print x#print y# create the plotplt.xlabel('time')plt.ylabel('HR')plt.plot(x, y, color='cyan', label='HR')plt.legend(loc='upper right', fontsize='small')plt.grid(True)#plt.title('Reading values from an Excel file'axes_1 = plt.subplot(G[1, :])x = np.zeros(sheet_1.max_row)y = np.zeros(len(x))for i in range(1, sheet_1.max_row):    x[i] = sheet_1.cell(row=i + 1, column=2).value    y[i] = sheet_1.cell(row=i + 1, column=6).value#print a#print b# create the plotplt.xlabel('time')plt.ylabel('Pulse')plt.plot(x, y, color='red', label='Pulse')plt.legend(loc='upper right', fontsize='small')plt.grid(True)axes_1 = plt.subplot(G[2, :])x = np.zeros(sheet_1.max_row)y = np.zeros(len(x))for i in range(1, sheet_1.max_row):    x[i] = sheet_1.cell(row=i + 1, column=2).value    y[i] = sheet_1.cell(row=i + 1, column=7).value#print x#print y# create the plotplt.xlabel('time')plt.ylabel('SpO2')plt.plot(x, y, color='magenta', label='SpO2')plt.legend(loc='upper right', fontsize='small')plt.grid(True)axes_1 = plt.subplot(G[3, :])x = np.zeros(sheet_1.max_row)y = np.zeros(len(x))for i in range(1, sheet_1.max_row):    x[i] = sheet_1.cell(row=i + 1, column=2).value    y[i] = sheet_1.cell(row=i + 1, column=8).value#print x#print y# create the plotplt.xlabel('time')plt.ylabel('Perf')plt.plot(x, y, color='blue', label='Perf')plt.legend(loc='upper right', fontsize='small')plt.grid(True)axes_1 = plt.subplot(G[4, :])x = np.zeros(sheet_1.max_row)y = np.zeros(len(x))for i in range(1, sheet_1.max_row):    x[i] = sheet_1.cell(row=i + 1, column=2).value    y[i] = sheet_1.cell(row=i + 1, column=9).value#print x#print y# create the plotplt.xlabel('time')plt.ylabel('etCO2')plt.plot(x, y, color='yellow', label='etCO2')plt.legend(loc='upper right', fontsize='small')plt.grid(True)axes_1 = plt.subplot(G[5, :])x = np.zeros(sheet_1.max_row)y = np.zeros(len(x))for i in range(1, sheet_1.max_row):    x[i] = sheet_1.cell(row=i + 1, column=2).value    y[i] = sheet_1.cell(row=i + 1, column=10).value#print x#print y# create the plotplt.xlabel('time')plt.ylabel('imCO2')plt.plot(x, y, color='green', label='imCO2')plt.legend(loc='upper right', fontsize='small')plt.grid(True)plt.xlim(0, 60000)plt.ylim(0, 100)plt.show()


import tkinter as tkfrom tkinter import filedialogimport pandas as pdimport matplotlib.pyplot as pltroot= tk.Tk()canvas1 = tk.Canvas(root, width = 300, height = 300, bg = 'lightsteelblue')canvas1.pack()def getExcel ():    global df        import_file_path = filedialog.askopenfilename()    df = pd.read_excel (import_file_path)    df["Year"] = pd.to_datetime(df["Year"], format="%Y")    ax = df.plot("Year", "Accidents",marker='o',color='r')    plt.grid()    plt.title('Yearly Graph')    ax.figure.autofmt_xdate()    plt.show()        browseButton_Excel = tk.Button(text='Import Excel File', command=getExcel, bg='green', fg='white', font=('helvetica', 12, 'bold'))canvas1.create_window(150, 150, window=browseButton_Excel)root.mainloop()