[[oktatas:programozás:python:wxpython_gui|< wxPython GUI]] ====== wxPython grid ====== * **Szerző:** Sallai András * Copyright (c) Sallai András, 2021 * Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]] * Web: https://szit.hu ===== Kép a cellába és mentés adatbázisba ===== import wx import wx.grid import mariadb class ImageRenderer(wx.grid.GridCellRenderer): def __init__(self, image): wx.grid.GridCellRenderer.__init__(self) self.image = image def Draw(self, grid, attr, dc, rect, row, col, isSelected): width = self.image.GetWidth() height = self.image.GetHeight() dc.SetBackgroundMode(wx.SOLID) tmp_dc = wx.MemoryDC() tmp_dc.SelectObject(self.image) if isSelected: dc.SetBrush(wx.Brush(wx.BLUE, wx.SOLID)) dc.SetPen(wx.Pen(wx.BLUE, 1, wx.SOLID)) else: dc.SetBrush(wx.Brush(wx.WHITE, wx.SOLID)) dc.SetPen(wx.Pen(wx.WHITE, 1, wx.SOLID)) dc.DrawRectangle(rect) if width > rect.width-2: width = rect.width-2 if height > rect.height-2: height = rect.height-2 dc.Blit(rect.x + 1, rect.y + 1, width, height, tmp_dc, 0, 0, wx.COPY, True) class MainFrame(wx.Frame): def __init__(self, parent): super(MainFrame, self).__init__(parent) self.grid = wx.grid.Grid(self) self.upload_button = wx.Button(self, label="Feltölt") self.save_button = wx.Button(self, label="Mentés") self.initUI() self.initLayout() def initUI(self): self.grid.CreateGrid(3, 3) self.grid.SetColLabelValue(0, "Név") self.grid.SetColLabelValue(1, "Település") self.grid.SetColLabelValue(2, "Kép") self.upload_button.Bind(wx.EVT_BUTTON, self.click_upload_button) self.save_button.Bind(wx.EVT_BUTTON, self.click_save_button) def initLayout(self): root_box = wx.BoxSizer(wx.VERTICAL) button_box = wx.BoxSizer(wx.HORIZONTAL) root_box.Add(self.grid) root_box.Add(button_box) button_box.Add(self.upload_button) button_box.Add(self.save_button) self.SetSizer(root_box) self.Layout() def click_upload_button(self, event): file_dialog = wx.FileDialog(self) if file_dialog.ShowModal() == wx.ID_OK: self.selected_file = file_dialog.GetPath(); self.set_image() file_dialog.Destroy() def click_save_button(self, event): self.save_to_database() def set_image(self): selection = [] selection += self.grid.GetSelectedRows() print(selection) image = wx.Bitmap(self.selected_file, wx.BITMAP_TYPE_ANY) imageRenderer = ImageRenderer(image) self.grid.SetCellRenderer(int(selection[0]),2,imageRenderer) self.SetTitle('Kép beállítva') def save_to_database(self): config = { 'host': 'localhost', 'user': 'test04', 'password': '12345' } conn = mariadb.connect(**config, database='test04') cur = conn.cursor() fp = open(self.selected_file, 'rb').read() sql = 'insert into tabla1(kep) values(%s)' args = (fp,) cur.execute(sql, args) conn.commit() conn.close() self.SetTitle('Mentés adatbázisba kész') class SimpleApp(wx.App): def OnInit(self): frame = MainFrame(None) frame.Show() return True app = SimpleApp() app.MainLoop()