2016-11-30 274 views
-1

我刚刚开始在一个月前开始编写Python,现在正在进入Tkinter。我试图建立一个程序,用户可以打开Excel文件到Tkinter中,显示数据框,用户可以选择某种图形类型,插入X轴和Y轴的变量并绘制它。我已经使用PAGE构建了GUI的总体布局,但在显示数据框和绘制图表时如何给这些小部件提供命令时遇到了问题。在Tkinter中打开excel文件并绘图

这里是我的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参与那里写这些代码。我所能做的只是给'Browse'按钮命令来搜索excel文件。

self.Button3.configure(command=askopenfilename) 

有人可以帮助我:

  1. 如何从指令选择的Excel文件保存到数据帧
  2. 如何显示数据框入框的下面
  3. 如何绘制图表选择在底部画布上的标准(图形和轴的类型)

非常感谢广告万斯。

+1

'命令=​​ my_own_function_to_open_file_and_do_other_things' – furas

+0

@furas我已经想过这个问题,但我会如何传递变量或dataframes从功能到其它的功能呢? –

+1

直接在这个函数中调用其他函数。或者使用'self.variable'来保存信息。 – furas

回答

0

在课堂上使用一些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() 
+0

是的,谢谢!我需要的只是一个明确的例子,谢谢(:最后一个问题,你不知道如何将图形绘制到画布上吗? –

+0

pandas使用matplotlib可以使用不同的GUI - tkinter,wxPython ,PyQt - 你必须在matplot中设置你使用的GUI,它可以让你访问你可以嵌入到GUI中的小部件(带图)。https://pythonprogramming.net/how-to-embed-matplotlib-graph- TKinter的GUI / – furas

0

这里,我已经取了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()