Search code examples
textboxwxpythonself

wxPython: write SQL command results to outputbox


I'm trying to get back into Python and I'm once again stuck with this problem I've had before of making objects accessible to one another. In this simple example I am displaying a panel with a button and a text box. Clicking on the text box calls a function which queries a database and returns a cursor with the retrieved data. I need to make it so that either the LookupSQL function or the ShowClientData function can write this output, in a loop, to the Text box. The TextBox (outputBox) is unknown to any other functions currently. How do I make it so that the other functions know what it is?

import wx
import pypyodbc
conn = pypyodbc.connect(driver='{SQL Server}', server='.', database='TheDB', uid='sa', pwd='Pass')


class Audit(wx.Frame):

def __init__(self, *args, **kwargs):
    super(Example, self).__init__(*args, **kwargs) 

    self.InitUI()

def InitUI(self):    

    panel = wx.Panel(self)

    hbox = wx.BoxSizer()
    sizer = wx.GridSizer(6,1,2,2)

    btn1 = wx.Button(panel, label='Clients')

    outputBox = wx.TextCtrl(panel, -1, style = wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL)
    sizer.AddMany([btn1, btn2, btn3, btn4, btn5, btn6])

    hbox.Add(sizer, 0, wx.ALL, 15)
    hbox.Add(outputBox, 1, wx.EXPAND)


    panel.SetSizer(hbox)

    btn1.Bind(wx.EVT_BUTTON, self.ShowClientData)

    self.SetSize((800, 600))
    self.SetTitle('Audit View')
    self.Centre()
    self.Show(True)


def ShowClientData(self, event):
    SQL = 'select * from V_UpdatedClient'
    recursor = lookupSQL(SQL)
    for row in recursor:
        rChange = row[0]
        rItemType = row[1]
        rPK = row[2]
        rItemCode = row[3]
        rFieldName = row[4]
        rOldValue = row[5]
        rNewValue = row[6]
        rUpdateDate = row[7]
        rUserName = row[8]
        print('%s %s %s %s %s %s %s %s %s' % (rChange, rItemType, rPK, rItemCode, rFieldName, rOldValue, rNewValue, rUpdateDate, rUserName))


def lookupSQL(SQLString):       
  cursor = conn.cursor()
  cursor.execute(SQLString)

  return cursor        
  cursor.close()


def main():

  ex = wx.App()
  Audit(None)
  ex.MainLoop()    


if __name__ == '__main__':
  main() 

Solution

  • What you are looking for is called data attributes.

    self.outputBox = wx.TextCtrl(panel, -1, style = wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL)
    

    And then within ShowClientData you can write

    self.outputBox.AppendText("some text")

    As long as you have that self reference, you can access its attributes.

    Edit:

    When you do the above change, you can't refer to the text box by just outputBox anymore, you should instead access it via self:

    hbox.Add(self.outputBox, 1, wx.EXPAND)

    Declaring it as globally is very bad!