본문 바로가기
Programming/Python_Etc

wxPython Grid에 pandas dataframe 출력하기

by Wilkyway 2020. 6. 23.
반응형
import wx
import wx.grid as gridlib
import os
import psycopg2
import pandas as pd


class MyFrame(wx.Frame):
    def __init__(self):

        #--------  1. GUI 초기화
        wx.Frame.__init__(self, parent=None, title="DB to Table")
        self.SetSize(1020, 600)
        self.mainPanel = wx.Panel(self)
        self.vtBoxSizer = wx.BoxSizer(wx.VERTICAL)  # 전체 레이아웃
        self.vhBoxSizer = wx.BoxSizer(wx.HORIZONTAL)  # 전체 레이아웃

        self.query_txt = wx.TextCtrl(self.mainPanel, -1, size=(400, 25))
        self.submit = wx.Button(self.mainPanel, -1, "Search")
        self.submit.Bind(wx.EVT_BUTTON, self.onSearch)

        # -------- 2. DB 연결
        self.conn = psycopg2.connect("host = localhost dbname=postgres user=postgres password=asdf4416 port=5432")
        self.cursor = self.conn.cursor()

        #--------- 3. Table Grid생성
        self.dataGrid = gridlib.Grid(self.mainPanel, wx.EXPAND)
        self.dataGrid.CreateGrid(50, 20)
        #self.dataGrid.AutoSize()
        #self.dataGrid.AutoSizeColumn(2, setAsMin=True)

        #--------- 5. GUI Show
        self.vhBoxSizer.Add(self.query_txt)
        self.vhBoxSizer.Add(self.submit)
        self.vtBoxSizer.Add(self.vhBoxSizer, 1, wx.EXPAND | wx.ALL)
        self.vtBoxSizer.Add(self.dataGrid, 1, wx.EXPAND|wx.ALL)
        self.mainPanel.SetSizer(self.vtBoxSizer)

    def onSearch(self, e):
        query = self.query_txt.GetValue()
        self.cursor.execute(query)
        result = self.cursor.fetchall()

        # ----------4. 결과를 dataframe으로 저장
        df = pd.DataFrame(result)
        for a in range(0, len(df.columns),1):
            print(df.columns[a])
            self.dataGrid.SetColLabelValue(a, str(df.columns[a]))

        for i in range(0, len(df), 1):  # 열 사이즈 참조
            for j in range(0, len(df.columns), 1):  # 행 사이즈 참조
                self.dataGrid.SetCellValue(i, j, str(df.loc[i][j]))
                # 셀 값 참조. 칼럼에 따라 숫자와 문자열이 혼재하지만 SetCellValue 의 세번째 인자가 문자열을 받아들임


if __name__ == "__main__":
    app = wx.App()
    frm = MyFrame()
    frm.Show()
    app.MainLoop()

반응형

'Programming > Python_Etc' 카테고리의 다른 글

Pyside2  (0) 2020.12.29
파이썬 matplotlib 차트 그리기 예시  (0) 2020.08.17
wxpython GridBagSizer 예제  (0) 2020.06.21
pandas CSV파일 읽기 - 인코딩 에러  (0) 2020.06.21
wxpython 폴더 트리 컨트롤  (0) 2020.06.18

댓글