DBから参照してグラフを描写するtkinter APP

DBから参照してグラフを描写するtkinter APP。

```python
import configparser
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter import filedialog as tkFileDialog
from datetime import date, datetime as dt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

input_list = ['tickers', 'freq', 'fields',
              'date_start', 'date_end', 'graph_type']
fig_dict = dict()


def get_settings():
    ret = {}
    for i in range(len(input_list)):
        ret[input_list[i]] = input_items[input_list[i]]['Entry'].get()
    return ret


def read_infile(path='./init_config.ini'):
    inifile = configparser.ConfigParser()
    inifile.read(path, 'UTF-8')
    return {ret: inifile.get('settings', ret) for ret in input_list}


def open_file():
    fTyp = [("", ".ini")]
    try:
        iDir = os.path.abspath(os.path.dirname(__file__))
    except:
        iDir = r'C:'
    file_path = tkFileDialog.askopenfilename(filetypes=fTyp, initialdir=iDir)
    if file_path != None:
        list_init_text = read_infile(file_path)
        for each_item in input_list:
            input_items[each_item]['Entry'].delete(0, END)
            input_items[each_item]['Entry'].insert(
                0, list_init_text[each_item])


def save_file():
    config = configparser.ConfigParser()
    file = tkFileDialog.asksaveasfile(mode='w', defaultextension='.ini')
    if file is None:
        return
    config['settings'] = get_settings()
    with open(file.name, 'w') as config_file:
        config.write(config_file)


def get_data(ret):
    # this is for qiita. We download data from DB.
    date_list = [dt(2018, 9, 1, 0, 0), dt(2018, 9, 2, 0, 0),
                 dt(2018, 9, 3, 0, 0), dt(2018, 9, 4, 0, 0)]
    field_list = ['Sales', 'OP']
    ret = np.random.rand(len(date_list), len(field_list))
    df = pd.DataFrame(ret, index=date_list, columns=field_list)
    return df


def plot_figure(df, str_graph_type='plot'):  # str_graph_type='bar', 'scatter' etc
    fig = Figure(figsize=(20, 6), dpi=100)
    ax1 = fig.add_subplot(1, 1, 1)
    for each in df.columns:
        eval('ax1.'+str_graph_type)(pd.to_datetime(df.index),
                                    df[each], label=each)
    ax1.legend()
    ax1.grid()
    return fig


def draw_graph():
    ret_settings = get_settings()
    df = get_data(ret_settings)
    img = plot_figure(df, str_graph_type=ret_settings['graph_type'])

    new = tk.Tk()
    new.geometry('600x400')
    root.title('output')
    canvas = FigureCanvasTkAgg(figure=img, master=new)
    canvas.get_tk_widget().pack(side=tk.BOTTOM, expand=0)
    canvas._tkcanvas.pack(side=tk.BOTTOM, expand=0)
    canvas.draw()
    new.attributes('-topmost', True)


# root frame
root = tk.Tk()
root.title('graph')
root.geometry('300x300')

# note book
nb = ttk.Notebook(width=600, height=200)

# making tabs
tabs = ['setting']
tab = [tk.Frame(nb) for i in range(len(tabs))]
for i in range(len(tabs)):
    nb.add(tab[i], text=tabs[i], padding=3)
nb.pack(expand=1, fill='both')

# making setting tabs
ret_tab = tab[tabs.index('setting')]

input_items = {input_list[i]: {} for i in range(len(input_list))}
list_init_text = read_infile()
list_init_text['date_end'] = date.today().strftime('%Y%m%d')

for each_item, i in zip(input_list, range(len(input_items))):
    input_items[each_item]['Lable'] = Label(ret_tab, text=input_list[i])
    input_items[each_item]['Entry'] = Entry(ret_tab)
    input_items[each_item]['Entry'].insert(END, list_init_text[each_item])
    [input_items[each_item][ret].grid(row=i+1, column=j)
     for ret, j in zip(['Lable', 'Entry'], range(2))]

ticker_load_button = Button(ret_tab, text='...')
ticker_load_button.grid(row=input_list.index('tickers')+1, column=2)

open_button = Button(ret_tab, text='Open', command=open_file)
open_button.grid(row=0, column=0, sticky=tk.W + tk.E)
draw_button = Button(ret_tab, text='Draw', command=draw_graph)
draw_button.grid(row=0, column=1, sticky=tk.W + tk.E)
save_button = Button(ret_tab, text='Save', command=save_file)
save_button.grid(row=0, column=2, sticky=tk.W + tk.E)

root.attributes('-topmost', True)
root.mainloop()
```

シンプルにグラフだけ表示

```python
def draw_graph(fig,geometry='600x400',title='output'):
    """
    import tkinter as tk
    from tkinter import *
    """
    root = tk.Tk()
    root.geometry('600x400')
    root.title('output')
    canvas = FigureCanvasTkAgg(figure=fig, master=root)
    canvas.get_tk_widget().pack(side=tk.BOTTOM, expand=0)
    canvas._tkcanvas.pack(side=tk.BOTTOM, expand=0)
    canvas.draw()
    root.attributes('-topmost', True)
    root.mainloop()
```