pydata

Keep Looking, Don't Settle

Tkinter read data, dropdown menu, select data and print dataframe

这个project主要是用Tkinter来读入csv/excel数据,然后根据读入的数据某一列或者某几列的唯一值建立下拉列表(dropdown menu),然后根据下拉列表选定的值来选取子数据并且把子数据打印出来

主要用到的东西

  1. 使用tkFileDialog.askopenfilename()产生窗口来读入文件,为了让读入的文件方便调用,把它global

  2. 读入文件确认以后,弹出新的页面,包括下拉列表(tk.OptionMenu),下拉列表set值(tk.StringVar),然后要返回选定的值(get)

  3. 下拉列表的值传递回去用来选择子数据

  4. 把选定的子数据作为string, pandas很方便的有to_string()

  5. 最后把字符(包括DataFrame)打印出来tex.insert(tk.END, s)

  6. 打印出来很大的话需要scroll tex.see(tk.END)

    Graph1. 开始页面,点击Read in Data会弹出读取文件的对话框

alt text

Graph 2. 读取文件的对话框

alt text

Graph 3.  打印出数据(string)

alt text

python code:
import Tkinter as tk
import ttk
import pandas as pd
import numpy as np
import tkFileDialog

'''
目的: 在startPage上添加一个输入框,然后把输入的值在传递到pageOne打印出来

步骤: 1.在startPage上添加一个Entry widget作为输入
     2.在myFrame添加get_page函数来获取页面
     3.最后在pageOne获取页面,从而获得value并打印出来
'''


class myFrame1(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)
        container.pack(side = "top", fill = "both", expand = True)  #
        container.grid_rowconfigure(0, weight = 1)
        container.grid_columnconfigure(0, weight = 1)

        self.frames = {}

        frame = startPage(container, self)  #startPage继承了container
        frame.grid(row=0, column=0, sticky="nsew")
        self.frames[startPage] = frame

        self.show_frame(startPage)

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        frame.tkraise()




class startPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller


        label = tk.Label(self, text = "-------------StartPage: This is the draft -------------------")
        label.pack(pady = 10, padx = 10)

        b0 = tk.Button(self, text="Read in Data", command = self.readData )
        b0.pack(padx=5, pady=5)
        b0.config(width = 30, bg = 'GRAY')

        # 在__init__下面,可以写self.controller或者controller,它们是一样的
        # 但是在上面的show_frame(不在__init__下),那么就需要self.frames,要不然找不到frames
        b1 = tk.Button(self, text = "Agree and go to next page", command = test)
        b1.pack()


    tkcalc = pd.DataFrame()
    tkidname = ['0-----0']

    def readData(self):
        global tkcalc
        global tkidname
        filename = tkFileDialog.askopenfilename()
        tkcalc = pd.read_excel(filename, sheetname = "Sheet1")
        tkidname =  [str(x[0]) + '------' +  str(x[1]) for x in tkcalc.ix[:, :2].drop_duplicates().values.tolist()]
        print tkcalc.head()


def test():

    # df = pd.DataFrame(np.random.randn(20, 15), columns=list('ABCDEFGHIJKLMNO'))



    def cbc(tex):
        return lambda : callback(tex)

    def callback(tex):
        myreturn = var1.get().split('------')[0]
        df = tkcalc.ix[tkcalc.loanid == int(myreturn), 2:]
        s = '-'*80 + "print of loanid = " + var1.get() + '-'*60 + "\n"*2 + df.to_string(index = False) + "\n"*3
        tex.insert(tk.END, s)
        tex.see(tk.END)             # Scroll if necessary

    popup = tk.Tk()
    tex = tk.Text(master=popup, width=240, height=50)
    tex.pack(side='bottom', expand = True)

    lst1 = tkidname
    var1 = tk.StringVar(popup)
    var1.set(lst1[0])
    dropdown = tk.OptionMenu(popup, var1, *lst1)
    dropdown.config(width = 60, bg = 'GREEN')
    dropdown.pack(side='top', padx=5, pady=5)


    b = tk.Button(popup, text="Print Select Loan Calculation", command=cbc(tex) )
    b.pack(padx=5, pady=5)
    b.config(width = 30, bg = 'GRAY')

    b1 = tk.Button(popup, text='Exit Program', command=popup.destroy)
    b1.pack(padx=5, pady=5)
    b1.config(width = 30, bg = 'WHITE')
    popup.mainloop()



app1 = myFrame1()
app1.mainloop()

### reference
# http://stackoverflow.com/questions/14879916/python-tkinter-make-any-output-appear-in-a-text-box-on-gui-not-in-the-shell
# https://www.daniweb.com/programming/software-development/threads/391736/how-to-add-a-drop-down-menu-and-return-the-selected-option
# http://www.prasannatech.net/2009/06/tkinter-optionmenu-changing-choices.html