在Tkinter中打开excel文件并绘制图表

时间:2016-11-30 02:08:31

标签: excel python-3.x plot tkinter widget

我一个月前刚开始写Python,现在进入Tkinter。我正在尝试构建一个程序,用户可以将excel文件打开到Tkinter,显示数据框,用户可以选择某种图形类型,插入X轴和Y轴的变量并绘制它。我使用PAGE构建了GUI的总体布局,但在如何在显示数据框和绘制图形时向窗口小部件发出命令方面存在问题。

这是我的GUI代码:

import sys
from tkinter.filedialog import askopenfilename

try:
    from Tkinter import *
except ImportError:
    from tkinter import *

try:
    import ttk
    py3 = 0
except ImportError:
    import tkinter.ttk as ttk
    py3 = 1

def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = Tk()
    top = New_Toplevel_1 (root)
    root.mainloop()

w = None
def create_New_Toplevel_1(root, *args, **kwargs):
    '''Starting point when module is imported by another program.'''
    global w, w_win, rt
    rt = root
    w = Toplevel (root)
    top = New_Toplevel_1 (w)
    return (w, top)

def destroy_New_Toplevel_1():
    global w
    w.destroy()
    w = None

class New_Toplevel_1:
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        self._bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        self._fgcolor = '#000000'  # X11 color: 'black'
        self._compcolor = '#d9d9d9' # X11 color: 'gray85'
        self._ana1color = '#d9d9d9' # X11 color: 'gray85' 
        self._ana2color = '#d9d9d9' # X11 color: 'gray85' 

        top.geometry("757x1037+832+67")
        top.title("New Toplevel 1")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")


        self.Canvas1 = Canvas(top)
        self.Canvas1.place(relx=0.04, rely=0.58, relheight=0.4, relwidth=0.92)
        self.Canvas1.configure(background="white")
        self.Canvas1.configure(borderwidth="2")
        self.Canvas1.configure(highlightbackground="#d9d9d9")
        self.Canvas1.configure(highlightcolor="black")
        self.Canvas1.configure(insertbackground="black")
        self.Canvas1.configure(relief=RIDGE)
        self.Canvas1.configure(selectbackground="#c4c4c4")
        self.Canvas1.configure(selectforeground="black")
        self.Canvas1.configure(width=695)

        self.Button2 = Button(top)
        self.Button2.place(relx=0.75, rely=0.52, height=42, width=138)
        self.Button2.configure(activebackground="#d9d9d9")
        self.Button2.configure(activeforeground="#000000")
        self.Button2.configure(background="#d9d9d9")
        self.Button2.configure(disabledforeground="#a3a3a3")
        self.Button2.configure(foreground="#000000")
        self.Button2.configure(highlightbackground="#d9d9d9")
        self.Button2.configure(highlightcolor="black")
        self.Button2.configure(pady="0")
        self.Button2.configure(text='''Generate Graph''')

        self.Labelframe1 = LabelFrame(top)
        self.Labelframe1.place(relx=0.05, rely=0.39, relheight=0.18
                , relwidth=0.44)
        self.Labelframe1.configure(relief=GROOVE)
        self.Labelframe1.configure(foreground="black")
        self.Labelframe1.configure(text='''Type of Graph''')
        self.Labelframe1.configure(background="#d9d9d9")
        self.Labelframe1.configure(highlightbackground="#d9d9d9")
        self.Labelframe1.configure(highlightcolor="black")
        self.Labelframe1.configure(width=330)

        self.Radiobutton1 = Radiobutton(self.Labelframe1)
        self.Radiobutton1.place(relx=0.06, rely=0.22, relheight=0.2
                , relwidth=0.31)
        self.Radiobutton1.configure(activebackground="#d9d9d9")
        self.Radiobutton1.configure(activeforeground="#000000")
        self.Radiobutton1.configure(background="#d9d9d9")
        self.Radiobutton1.configure(disabledforeground="#a3a3a3")
        self.Radiobutton1.configure(foreground="#000000")
        self.Radiobutton1.configure(highlightbackground="#d9d9d9")
        self.Radiobutton1.configure(highlightcolor="black")
        self.Radiobutton1.configure(justify=LEFT)
        self.Radiobutton1.configure(text='''Bar Chart''')

        self.Radiobutton2 = Radiobutton(self.Labelframe1)
        self.Radiobutton2.place(relx=0.06, rely=0.38, relheight=0.2
                , relwidth=0.35)
        self.Radiobutton2.configure(activebackground="#d9d9d9")
        self.Radiobutton2.configure(activeforeground="#000000")
        self.Radiobutton2.configure(background="#d9d9d9")
        self.Radiobutton2.configure(disabledforeground="#a3a3a3")
        self.Radiobutton2.configure(foreground="#000000")
        self.Radiobutton2.configure(highlightbackground="#d9d9d9")
        self.Radiobutton2.configure(highlightcolor="black")
        self.Radiobutton2.configure(justify=LEFT)
        self.Radiobutton2.configure(text='''Histogram''')

        self.Radiobutton3 = Radiobutton(self.Labelframe1)
        self.Radiobutton3.place(relx=0.06, rely=0.54, relheight=0.2
                , relwidth=0.37)
        self.Radiobutton3.configure(activebackground="#d9d9d9")
        self.Radiobutton3.configure(activeforeground="#000000")
        self.Radiobutton3.configure(background="#d9d9d9")
        self.Radiobutton3.configure(disabledforeground="#a3a3a3")
        self.Radiobutton3.configure(foreground="#000000")
        self.Radiobutton3.configure(highlightbackground="#d9d9d9")
        self.Radiobutton3.configure(highlightcolor="black")
        self.Radiobutton3.configure(justify=LEFT)
        self.Radiobutton3.configure(text='''Scatter Plot''')

        self.Button3 = Button(top)
        self.Button3.place(relx=0.28, rely=0.05, height=52, width=122)
        self.Button3.configure(activebackground="#d9d9d9")
        self.Button3.configure(activeforeground="#000000")
        self.Button3.configure(background="#d9d9d9")
        self.Button3.configure(disabledforeground="#a3a3a3")
        self.Button3.configure(foreground="#000000")
        self.Button3.configure(highlightbackground="#d9d9d9")
        self.Button3.configure(highlightcolor="black")
        self.Button3.configure(pady="0")
        self.Button3.configure(text='''Browse''')
        self.Button3.configure(width=122)
        self.Button3.configure(command=askopenfilename)

        self.Label5 = Label(top)
        self.Label5.place(relx=0.03, rely=0.06, height=31, width=147)
        self.Label5.configure(activebackground="#f9f9f9")
        self.Label5.configure(activeforeground="black")
        self.Label5.configure(background="#d9d9d9")
        self.Label5.configure(disabledforeground="#a3a3a3")
        self.Label5.configure(foreground="#000000")
        self.Label5.configure(highlightbackground="#d9d9d9")
        self.Label5.configure(highlightcolor="black")
        self.Label5.configure(text='''Upload File:''')
        self.Label5.configure(width=147)

        self.Label3 = Label(top)
        self.Label3.place(relx=0.05, rely=0.13, height=31, width=111)
        self.Label3.configure(background="#d9d9d9")
        self.Label3.configure(disabledforeground="#a3a3a3")
        self.Label3.configure(foreground="#000000")
        self.Label3.configure(text='''Data Frame :''')

        self.Text1 = Text(top)
        self.Text1.place(relx=0.05, rely=0.16, relheight=0.21, relwidth=0.9)
        self.Text1.configure(background="white")
        self.Text1.configure(font="TkTextFont")
        self.Text1.configure(foreground="black")
        self.Text1.configure(highlightbackground="#d9d9d9")
        self.Text1.configure(highlightcolor="black")
        self.Text1.configure(insertbackground="black")
        self.Text1.configure(selectbackground="#c4c4c4")
        self.Text1.configure(selectforeground="black")
        self.Text1.configure(width=684)
        self.Text1.configure(wrap=WORD)

        self.Labelframe2 = LabelFrame(top)
        self.Labelframe2.place(relx=0.5, rely=0.39, relheight=0.12
                , relwidth=0.45)
        self.Labelframe2.configure(relief=GROOVE)
        self.Labelframe2.configure(foreground="black")
        self.Labelframe2.configure(text='''Labelframe''')
        self.Labelframe2.configure(background="#d9d9d9")
        self.Labelframe2.configure(width=340)

        self.Label1 = Label(self.Labelframe2)
        self.Label1.place(relx=0.03, rely=0.24, height=31, width=67)
        self.Label1.configure(background="#d9d9d9")
        self.Label1.configure(disabledforeground="#a3a3a3")
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(text='''X-axis :''')

        self.Label2 = Label(self.Labelframe2)
        self.Label2.place(relx=0.03, rely=0.56, height=31, width=66)
        self.Label2.configure(background="#d9d9d9")
        self.Label2.configure(disabledforeground="#a3a3a3")
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(text='''Y-axis :''')

        self.Entry1 = Entry(self.Labelframe2)
        self.Entry1.place(relx=0.24, rely=0.24, relheight=0.29, relwidth=0.72)
        self.Entry1.configure(background="white")
        self.Entry1.configure(disabledforeground="#a3a3a3")
        self.Entry1.configure(font="TkFixedFont")
        self.Entry1.configure(foreground="#000000")
        self.Entry1.configure(insertbackground="black")
        self.Entry1.configure(width=244)

        self.Entry2 = Entry(self.Labelframe2)
        self.Entry2.place(relx=0.24, rely=0.56, relheight=0.29, relwidth=0.72)
        self.Entry2.configure(background="white")
        self.Entry2.configure(disabledforeground="#a3a3a3")
        self.Entry2.configure(font="TkFixedFont")
        self.Entry2.configure(foreground="#000000")
        self.Entry2.configure(insertbackground="black")
        self.Entry2.configure(width=244)

if __name__ == '__main__':
    vp_start_gui()

我知道如何将数据保存到数据框中并在Python中绘制图表,但我不确定在涉及GUI时编写这些代码的位置。我所能做的就是给“浏览”一个命令。用于搜索excel文件的按钮。

self.Button3.configure(command=askopenfilename)

有人可以帮助我:

  1. 如何将从命令中选择的Excel文件保存到数据框
  2. 如何将数据框显示在下面的文本框中
  3. 如何使用在底部画布上选择的标准(图形和轴的类型)绘制图形
  4. 非常感谢。

3 个答案:

答案 0 :(得分:2)

这里我获取了excel数据并将其存储在图表中,但我希望我的图表应该在5秒后绘制数据,并且图表应该在运行时运行。

from openpyxl import load_workbook
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# read  from excel file
wb = 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 plot
plt.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 plot
plt.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 plot
plt.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 plot
plt.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 plot
plt.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 plot
plt.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()

答案 1 :(得分:1)

在课堂上使用一些self.variable来保存信息,然后你可以在课堂上的其他方法中使用它。

在示例中,我使用方法load()加载文件并创建数据框,使用方法display()在文本小部件中显示此数据框。

try:
    # Python 2
    import Tkinter as tk
    import ttk
    from tkFileDialog import askopenfilename
except ImportError:
    # Python 3
    import tkinter as tk
    from tkinter import ttk
    from tkinter.filedialog import askopenfilename

import 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()

答案 2 :(得分:1)

将tkinter导入为tk 从tkinter导入文件对话框 将熊猫作为pd导入 导入matplotlib.pyplot作为plt

root = tk.Tk()

canvas1 = tk.Canvas(根,宽度= 300,高度= 300,bg ='lightsteelblue') canvas1.pack()

def getExcel():     全局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(文本='导入Excel文件',command = getExcel,bg ='绿色',fg ='白色',字体=('helvetica',12,'bold')) canvas1.create_window(150,150,window = browseButton_Excel)

root.mainloop()