2016-11-30 35 views
-1

私はちょうど1ヶ月前にPythonを書いて、今Tkinterに入っています。私は、ユーザーがTkinterにExcelファイルを開き、データフレームを表示し、ユーザーが特定のグラフタイプを選択し、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. の下にテキストボックスにデータフレームを表示する方法キャンバスの底に選択された基準(グラフと軸のタイプ)を持つグラフ

ありがとうございましたヴァンス。

+1

私はそれについて考えてきましたが、その後どのように私は他の関数にその関数から変数またはデータフレームを渡すのでしょうか? 'コマンド= my_own_function_to_open_file_and_do_other_things' – furas

+0

@furas –

+1

他の関数を直接この関数で呼び出します。あるいは、 'self.variable'を使って情報を保持してください。 – furas

答えて

0

クラスでは、情報を保持するためにいくつかのself.variableを使用して、クラス内の他のメソッドで使用することができます。

例では、ファイルをロードしてデータフレームを作成し、このデータフレームをテキストウィジェットに表示するにはload()メソッドを使用します。

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は、さまざまなGUIで動作するmatplotlibを使用します - 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() 
関連する問題