Writing to a a second frame from first Frame using wxPython - python

First attempt at a GUI using wxpython. I am trying to write from the main frame "MyForm" to a second Frame which is a gridlayout form. I keep running into:
AttributeError: 'MyForm' object has no attribute 'myGrid'
Below is my code, error happens at line 120. I relize that it is stuck in MyForm, I am just not sure how to get out of it.
import wx
import wx.grid as gridlib
import csv
import datetime
import re
today = datetime.date.today()
month = str(today.month -1)
year = str(today.year)
regex = re.compile(month +'/../'+year)
regex2 = re.compile(month +'/./'+year)
rootCause = ['COMPONENT DEFECT','EMC PROCESS DEFECT','METAL DEFECT','NFF','OTHER','VENDOR PROCESS DEFECT']
class gridForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Drill Down Data", size = (1000,1000))
panel = wx.Panel(self)
self.myGrid = gridlib.Grid(panel)
self.myGrid.CreateGrid(12, 8)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.myGrid, 1, wx.EXPAND)
panel.SetSizer(self.sizer)
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "627 Data", size = (1000,1000))
panel = wx.Panel(self, wx.ID_ANY)
self.monthButton = wx.Button(panel, pos = (250,5), id=wx.ID_ANY, label="Last Month")
self.monthButton.Bind(wx.EVT_BUTTON, self.lastMonth)
self.compButton = wx.Button(panel, pos = (250,50), id=wx.ID_ANY, label="COMPONENT DEFECT")
self.compButton.Bind(wx.EVT_BUTTON, self.compMonth)
self.emcButton = wx.Button(panel, pos = (250,75), id=wx.ID_ANY, label="EMC PROCESS DEFECT")
self.emcButton.Bind(wx.EVT_BUTTON, self.lastMonth)
self.metalButton = wx.Button(panel, pos = (250,100), id=wx.ID_ANY, label="METAL DEFECT")
self.metalButton.Bind(wx.EVT_BUTTON, self.lastMonth)
self.nffButton = wx.Button(panel, pos = (250,125), id=wx.ID_ANY, label="NFF")
self.nffButton.Bind(wx.EVT_BUTTON, self.lastMonth)
self.otherButton = wx.Button(panel, pos = (250,150), id=wx.ID_ANY, label="OTHER")
self.otherButton.Bind(wx.EVT_BUTTON, self.lastMonth)
self.vendorButton = wx.Button(panel, pos = (250,175), id=wx.ID_ANY, label="VENDOR PROCESS DEFECT")
self.vendorButton.Bind(wx.EVT_BUTTON, self.lastMonth)
self.partLabel = wx.StaticText(panel,100, 'Part number', pos = (15,10))
self.partText = wx.TextCtrl(panel, pos = (100,5), size = (100,-1))
self.partText.SetInsertionPoint(0)
self.compText = wx.TextCtrl(panel, pos = (100,50), size = (100,-1))
self.compText.SetInsertionPoint(0)
self.emcText = wx.TextCtrl(panel, pos = (100,75), size = (100,-1))
self.emcText.SetInsertionPoint(0)
self.metalText = wx.TextCtrl(panel, pos = (100,100), size = (100,-1))
self.metalText.SetInsertionPoint(0)
self.nffText = wx.TextCtrl(panel, pos = (100,125), size = (100,-1))
self.nffText.SetInsertionPoint(0)
self.otherText = wx.TextCtrl(panel, pos = (100,150), size = (100,-1))
self.otherText.SetInsertionPoint(0)
self.vendorText = wx.TextCtrl(panel, pos = (100,175), size = (100,-1))
self.vendorText.SetInsertionPoint(0)
# self.Bind(wx.EVT_BUTTON, self.onButton, button)
#----------------------------------------------------------------------
def lastMonth(self, event):
partNumber = self.partText.GetValue()
if partNumber != "":
csvfile = open('C:\\627\Qual History.csv')
datareader = csv.reader(csvfile, delimiter = ',')
compCount = 0
emcCount = 0
metalCount = 0
nffCount = 0
otherCount = 0
vendorCount = 0
for row in datareader:
if re.match(regex,row[3]) or re.match(regex2,row[3]):
if (row[1] == partNumber and row[9] == 'COMPONENT DEFECT' ):
compCount += 1
elif (row[1] == partNumber and row[9] == 'EMC PROCESS DEFECT' ):
emcCount += 1
elif (row[1] == partNumber and row[9] == 'METAL DEFECT' ):
metalCount += 1
elif (row[1] == partNumber and row[9] == 'NFF' ):
nffCount += 1
elif (row[1] == partNumber and row[9] == 'OTHER' ):
otherCount += 1
elif (row[1] == partNumber and row[9] == 'VENDOR PROCESS DEFECT' ):
vendorCount += 1
self.compText.SetValue(str(compCount))
self.emcText.SetValue(str(emcCount))
self.metalText.SetValue(str(metalCount))
self.nffText.SetValue(str(nffCount))
self.otherText.SetValue(str(otherCount))
self.vendorText.SetValue(str(vendorCount))
print compCount, emcCount, metalCount, nffCount, otherCount, vendorCount
def compMonth(self, event):
partNumber = self.partText.GetValue()
csvfile = open('C:\\627\Qual History.csv')
datareader = csv.reader(csvfile, delimiter = ',')
compCount = 0
compFails = []
compFinal = {}
for row in datareader:
if re.match(regex,row[3]) or re.match(regex2,row[3]):
if (row[1] == partNumber and row[9] == 'COMPONENT DEFECT' ):
compCount += 1
compFails.append(row[7])
print compFails
for item in compFails:
compFinal[item] = compFails.count(item)
print compFinal
count = len(compFinal)
print count
self.myGrid.gridForm.SetCellValue(0,0, "Failure") #here is where ir starts
self.myGrid.SetCellValue(0,1, "Count")
self.myGrid.SetCellValue(0,3, "Percent Total")
frame = gridForm()
frame.Show()
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm()
frame.Show()
app.MainLoop()

myGrid is an attribute of gridForm class, that is why self.myGrid won't work from within MyForm, as in MyForm self is an instance of the class MyForm and not gridForm. There are many alternatives to what you want to accomplish. Two of these are:
you can wrap the calls to SetCellValue into a method of gridForm and call the new method as frame.SetCellValueWrapper()
as follows:
class gridForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Drill Down Data", size = (1000,1000))
panel = wx.Panel(self)
self.myGrid = gridlib.Grid(panel)
self.myGrid.CreateGrid(12, 8)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.myGrid, 1, wx.EXPAND)
panel.SetSizer(self.sizer)
def SetCellValueWrapper(self):
self.myGrid.SetCellValue(0,0, "Failure") #here is where ir starts
self.myGrid.SetCellValue(0,1, "Count")
self.myGrid.SetCellValue(0,3, "Percent Total")
def compMonth(self, event):
frame = gridForm()
frame.SetCellValueWrapper()
frame.Show()
or you can access myGrid directly and call the method.
like this
def compMonth(self, event):
frame = gridForm()
frame.myGrid.SetCellValue(0,0, "Failure") #here is where ir starts
frame.myGrid.SetCellValue(0,1, "Count")
frame.myGrid.SetCellValue(0,3, "Percent Total")
frame.Show()

Related

wx.media.MediaCtrl - problems with wx.media.EVT_MEDIA_STOP, wx.media.EVT_MEDIA_FINISHED and Load()

I am trying to make a player which will automatically play the next song from a list when the current one ends. Whatever I do, when I add a call to Load() in the on_song_end method of my class binded both to wx.media.EVT_MEDIA_STOP or wx.media.EVT_MEDIA_FINISHED, it hangs or just iterates through all the items indefinitely.
What am I doing wrong?
import os
import wx
from wx.media import MediaCtrl
from wx.adv import Sound
import wx.lib.mixins.listctrl as listmix
import eyed3
import glob
APP_TITLE = "Crazy ID3 tag editor"
class Window(wx.Frame, listmix.ColumnSorterMixin):
def __init__(self, *args, **kwargs):
super(Window, self).__init__(*args, **kwargs)
self.InitUI()
self.create_menu()
self.update_mp3_listing("D:\\YT")
self.itemDataMap = self.row_data
listmix.ColumnSorterMixin.__init__(self, 4)
def InitUI(self):
self.row_data = {}
self.row_obj_dict = {}
self.now_playing_index = -1
self.panel = wx.Panel(self)
self.panel.SetLabel(APP_TITLE)
self.mp3_list_label = wx.StaticText(self.panel, label="List of mp3's")
self.mp3_list = MyListCtrl(self.panel, id=wx.ID_ANY, size=(-1, -1), style=wx.LC_REPORT)
self.mp3_list.InsertColumn(0, "Artist", width=140)
self.mp3_list.InsertColumn(1, "Title", width=140)
self.mp3_list.InsertColumn(2, "Album", width=200)
self.mp3_list.InsertColumn(3, "Filename", width=200)
# self.mp3_list.InsertColumn(3, "Year", width=200)
self.mp3_list.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.on_list_item_activate)
self.mp3_list.Bind(wx.EVT_LIST_ITEM_FOCUSED, self.on_item_focused)
self.mp3_list.Bind(wx.EVT_LIST_COL_CLICK, self.on_col_click)
self.edit_button = wx.Button(self.panel, label="&Edit")
self.edit_button.Bind(wx.EVT_BUTTON, self.on_edit)
self.refresh_button = wx.Button(self.panel)
self.refresh_button.Bind(wx.EVT_BUTTON, self.refresh_mp3_listing)
self.refresh_button.Hide()
self.stop_button = wx.Button(self.panel)
self.stop_button.Bind(wx.EVT_BUTTON, self.stop_song)
self.stop_button.Hide()
self.focus_now_playing_button = wx.Button(self.panel)
self.focus_now_playing_button.Bind(wx.EVT_BUTTON, self.focus_now_playing)
self.focus_now_playing_button.Hide()
self.sizer = wx.GridBagSizer(5, 5)
self.sizer.Add(self.mp3_list_label, pos=(0, 0), span=(1, 2))
self.sizer.Add(self.mp3_list, pos=(1, 0), span=(1, 1), flag=wx.EXPAND|wx.ALL)
self.sizer.Add(self.edit_button, pos=(1, 1), span=(1, 1), flag=wx.ALL|wx.ALIGN_CENTER_HORIZONTAL)
self.sizer.AddGrowableRow(1)
self.sizer.AddGrowableCol(0, proportion=3)
self.sizer.AddGrowableCol(1, proportion=1)
self.panel.SetSizerAndFit(self.sizer)
self.Fit()
self.Center()
self.accelerator_table = wx.AcceleratorTable([(wx.ACCEL_NORMAL, wx.WXK_F5, self.refresh_button.GetId()), (wx.ACCEL_ALT, wx.WXK_CONTROL_S, self.stop_button.GetId()), (wx.ACCEL_NORMAL, wx.WXK_MEDIA_STOP, self.stop_button.GetId()), (wx.ACCEL_CTRL, wx.WXK_CONTROL_P, self.focus_now_playing_button.GetId())])
self.SetAcceleratorTable(self.accelerator_table)
self.Show(True)
def create_menu(self):
self.menu_bar = wx.MenuBar()
self.file_menu = wx.Menu()
self.open_folder_menu_item = self.file_menu.Append(wx.ID_ANY, "Op&en folder", "Open a folder with MP3s")
self.menu_bar.Append(self.file_menu, "&File")
self.Bind(wx.EVT_MENU, self.on_open_folder, self.open_folder_menu_item)
self.SetMenuBar(self.menu_bar)
def on_open_folder(self, event):
title = "Choose a directory: "
dlg = wx.DirDialog(self, title, style=wx.DD_DEFAULT_STYLE)
if dlg.ShowModal() == wx.ID_OK:
self.update_mp3_listing(dlg.GetPath())
dlg.Destroy()
def on_edit(self, event):
focused_item = self.mp3_list.GetFocusedItem()
selected_items_count = self.mp3_list.GetSelectedItemCount()
if focused_item >= 0:
if selected_items_count == 1:
if focused_item == self.now_playing_index:
self.stop_song(event=None)
mp3 = self.row_obj_dict[self.mp3_list.GetItemData(focused_item)]
dlg = EditDialog(mp3)
dlg.ShowModal()
self.update_mp3_listing(self.current_folder_path)
dlg.Destroy()
self.mp3_list.Focus(focused_item)
else:
mp3s_to_edit = []
item = self.mp3_list.GetFirstSelected()
while item != -1:
mp3 = self.row_obj_dict[self.mp3_list.GetItemData(item)]
mp3s_to_edit.append(mp3)
item = self.mp3_list.GetNextSelected(item)
dlg = EditArtistDialog(mp3s_to_edit)
dlg.ShowModal()
self.update_mp3_listing(self.current_folder_path)
dlg.Destroy()
self.mp3_list.Focus(focused_item)
def update_mp3_listing(self, folder_path):
self.current_folder_path = folder_path
self.mp3_list.ClearAll()
self.mp3_list.InsertColumn(0, "Artist", width=140)
self.mp3_list.InsertColumn(1, "Title", width=200)
self.mp3_list.InsertColumn(2, "Album", width=140)
self.mp3_list.InsertColumn(3, "Filename", width=200)
# self.mp3_list.InsertColumn(3, "Year", width=200)
mp3s = glob.glob(folder_path + "/*.mp3")
mp3_objects = []
index = 0
for mp3 in mp3s:
mp3_object = eyed3.load(mp3)
self.mp3_list.InsertItem(index, mp3_object.tag.artist or " ")
self.mp3_list.SetItem(index, 1, mp3_object.tag.title or " ")
self.mp3_list.SetItem(index, 2, mp3_object.tag.album or " ")
self.mp3_list.SetItem(index, 3, mp3)
self.mp3_list.SetItemData(index, index)
# self.mp3_list.SetItemData(index, [mp3_object.tag.artist or " ", mp3_object.tag.title or " ", mp3_object.tag.album or " ", mp3])
mp3_objects.append(mp3_object)
self.row_data[index] = (mp3_object.tag.artist or " ", mp3_object.tag.title or " ", mp3_object.tag.album or " ", mp3_object.tag.file_info.name)
self.row_obj_dict[index] = mp3_object
index += 1
def refresh_mp3_listing(self, event):
self.update_mp3_listing(self.current_folder_path)
def on_loaded(self, event):
self.player.Play()
# self.now_playing_index = self.mp3_list.GetItemData(self.mp3_list.GetFocusedItem()+1)
def on_list_item_activate(self, event):
focused_item = self.mp3_list.GetFocusedItem()
mp3 = self.row_obj_dict[self.mp3_list.GetItemData(focused_item)]
self.player = MediaCtrl(parent=self, szBackend=wx.media.MEDIABACKEND_WMP10)
self.player.Load(mp3.tag.file_info.name) # tried wx.CallAfter without success
self.player.SetVolume(0.25)
self.now_playing_index = focused_item
self.Bind(wx.media.EVT_MEDIA_LOADED, self.on_loaded, self.player)
self.Bind(wx.media.EVT_MEDIA_STOP, self.on_song_end, self.player)
if mp3.tag.artist and mp3.tag.title:
self.SetTitle(f"{APP_TITLE + ': ' + mp3.tag.artist + ' - ' + mp3.tag.title}")
else:
self.SetTitle(f"{APP_TITLE + ': ' + os.path.split(os.path.splitext(mp3.tag.file_info.name)[0])[1]} (no tags)")
def on_song_end(self, event):
self.player.Stop()
now = self.now_playing_index
if now < self.mp3_list.GetItemCount()-1:
song = self.row_obj_dict[self.mp3_list.GetItemData(now+1)]
self.now_playing_index = now+1
else:
song = self.row_obj_dict[self.mp3_list.GetItemData(0)]
self.now_playing_index = 0
print(song.tag.title)
#self.player.Stop()
wx.CallAfter(self.player.Load, song.tag.file_info.name)
"""
if song.tag.artist and song.tag.title:
self.SetTitle(f"{APP_TITLE + ': ' + song.tag.artist + ' - ' + song.tag.title}")
else:
self.SetTitle(f"{APP_TITLE + ': ' + os.path.split(os.path.splitext(song.tag.file_info.name)[0])[1]} (no tags)")
"""
def stop_song(self, event):
self.player.Pause()
self.now_playing_index = -1
self.SetTitle(APP_TITLE)
def focus_now_playing(self, event):
if self.now_playing_index >= 0:
self.mp3_list.Focus(self.now_playing_index)
self.mp3_list.Select(self.now_playing_index, on=1)
else:
Sound().PlaySound("c:/windows/media/Windows Ding.wav", wx.adv.SOUND_ASYNC)
# mixin methods override
def GetListCtrl(self):
return self.mp3_list
def on_col_click(self, event):
old_order = self.mp3_list.GetColumnsOrder()
self.mp3_list.SortItems(1)
new_order = old_order
clicked_column = new_order.pop(self.mp3_list.GetColumnIndexFromOrder(event.GetColumn()))
new_order.insert(0, clicked_column)
self.mp3_list.SetColumnsOrder(new_order)
self.mp3_list.RefreshItems(0, self.mp3_list.GetItemCount()-1)
# event.Skip()
def on_item_focused(self, event):
# print(self.mp3_list.GetItemData(self.mp3_list.GetFocusedItem()))
pass
class MyListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
def __init__(self, parent, id=wx.ID_ANY, autoSizeColumn="LAST", itemTextCallable=None, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0):
if itemTextCallable is not None:
if not isinstance(itemTextCallable, Callable):
raise TypeError("itemTextCallable should be None or a callable")
self._itemTextCallable = itemTextCallable
else:
self._itemTextCallable = self._super_itemTextCallable
wx.ListCtrl.__init__(self, parent, id=id, pos=pos, size=size, style=style)
listmix.ListCtrlAutoWidthMixin.__init__(self)
self.setResizeColumn(autoSizeColumn)
self.Bind(wx.EVT_WINDOW_DESTROY, source=self, id=self.GetId, handler=self._onDestroy)
def _onDestroy(self, evt):
evt.Skip()
self._itemTextCallable = None
def _super_itemTextCallable(self, item, column):
return super(MyListCtrl, self).OnGetItemText(item, column)
def OnGetItemText(self, item, column):
return self._itemTextCallable(item, column)
def sendListItemFocusedEvent(self, index):
evt = wx.ListEvent(wx.wxEVT_LIST_ITEM_FOCUSED, self.Id)
evt.EventObject = self
evt.Index = index
self.ProcessEvent(evt)
app = wx.App()
window = Window(None, title=APP_TITLE)
app.MainLoop()

Delete item in ListCtrl Python

How can I clear list ctrl in Python?
For example when I insert the 10's item the first 8 item are deleted from the listCtrl with the possibility to continue entering item in a listCtrl.
How can i do this?
Example:
I insert: 1,2,3,4,5,6,7,8,9,10 after the 10 item i see in the listCtrl only 8,9,10 and i can insert item again.
I put some code with my example.
import wx
import wx.gizmos as gizmos
import time
import datetime
from datetime import timedelta
class CWindow(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, style = wx.DEFAULT_FRAME_STYLE & ~ wx.CLOSE_BOX ^ wx.MAXIMIZE_BOX ^ wx.RESIZE_BORDER, size=(600,500))
dataCorrente = datetime.datetime.now()
self.Panel = wx.Panel(self, -1)
self.index = 0
self.ceck = {}
self.ts = ""
self.CTesto = wx.TextCtrl(self.Panel, 1, pos=(10,40), style=wx.TE_PROCESS_ENTER)
self.CTesto.Bind(wx.EVT_TEXT_ENTER,self.add_line)
self.BtnConferma = wx.Button(self.Panel, 12, "Conferma", pos=(130,38))
self.list_ctrl = wx.ListCtrl(self.Panel, pos=(10,90),size=(-1,330),style=wx.LC_REPORT|wx.BORDER_SUNKEN)
self.list_ctrl.InsertColumn(0, 'Name')
self.list_ctrl.InsertColumn(1, 'Start')
self.list_ctrl.InsertColumn(2, 'Finish', width=100)
wx.Button(self.Panel, 22, "Exit", pos=wx.Point(470,400))
self.Bind(wx.EVT_BUTTON, self.close, id=22)
self.Bind(wx.EVT_BUTTON, self.add_line, self.BtnConferma, id=12)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.list_ctrl, 0, wx.ALL|wx.EXPAND, 5)
sizer.Add(self.BtnConferma, 0, wx.ALL|wx.CENTER, 5)
self.led = gizmos.LEDNumberCtrl(self.Panel, -1, pos = (350,25), size = (200,50), style = gizmos.LED_ALIGN_CENTER)
self.led.SetBackgroundColour("#c0c0c0")
self.led.SetForegroundColour("black")
self.OnTimer(None)
self.timer = wx.Timer(self, -1)
self.timer.Start(1000)
self.Bind(wx.EVT_TIMER, self.OnTimer)
style = gizmos.LED_ALIGN_CENTER
def OnTimer(self, event):
current = time.localtime(time.time())
self.ts = time.strftime("%H:%M:%S", current)
self.led.SetValue(self.ts)
if self.ts in self.ceck:
self.list_ctrl.SetItemTextColour(self.ceck.get(self.ts), wx.WHITE)
self.list_ctrl.SetItemBackgroundColour(self.ceck.pop(self.ts), wx.RED)
def add_line(self,event):
val = str(self.CTesto.GetValue())
if val== '':
msg = wx.MessageDialog(self, "Error", "Error", wx.OK| wx.ICON_ERROR)
msg.ShowModal()
msg.Destroy()
else:
if self.list_ctrl.GetItemCount() == 10:
for i in range(7):
self.list_ctrl.DeleteItem(1)
dataCorrente = datetime.datetime.now()
oraAttuale =(dataCorrente.strftime("%H:%M:%S"))
plus = (datetime.datetime.strptime(oraAttuale, "%H:%M:%S") + datetime.timedelta(minutes=1))
global plus2
plus2 = plus.strftime("%H:%M:%S")
if plus2 in self.ceck:
msg = wx.MessageDialog(self, "Duplicate Time", "Error", wx.OK| wx.ICON_ERROR)
msg.ShowModal()
msg.Destroy()
return
self.list_ctrl.InsertItem(self.index, val)
self.list_ctrl.SetItem(self.index, 1, oraAttuale)
self.list_ctrl.SetItem(self.index, 2, str(plus2))
self.index += 1
InsVal = (val + " - " + oraAttuale + " - " + plus2 + '\n')
self.CTesto.Clear()
self.ceck[plus2] = self.index -1
def close(self,event):
hDialog=wx.MessageDialog(self, "°°°", "Exit", wx.OK|wx.CANCEL| wx.ICON_EXCLAMATION)
rispostaDialog=hDialog.ShowModal()
hDialog.Destroy()
if rispostaDialog == wx.ID_OK:
self.Destroy()
app = wx.App()
frame = CWindow(None, -1, "Example")
frame.Show()
frame.Center()
app.MainLoop()
You appear to have gone back (from your original post) to having the listctrl items in entry order rather than reverse entry order. That means that once again you have to remove index 0 and not index 1.
You are also not allowing for the fact that the dictionary values are now invalid if you just deleted 7 of the entries. They have to be removed if the item has been deleted and reset to the new index value if they have been left in place.
Try this, see if it gets you any closer to what you are trying to achieve:
import wx
import wx.gizmos as gizmos
import time
import datetime
from datetime import timedelta
class CWindow(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, style = wx.DEFAULT_FRAME_STYLE & ~ wx.CLOSE_BOX ^ wx.MAXIMIZE_BOX ^ wx.RESIZE_BORDER, size=(600,500))
dataCorrente = datetime.datetime.now()
self.Panel = wx.Panel(self, -1)
self.index = 0
self.ceck = {}
self.ts = ""
self.CTesto = wx.TextCtrl(self.Panel, 1, pos=(10,40), style=wx.TE_PROCESS_ENTER)
self.CTesto.Bind(wx.EVT_TEXT_ENTER,self.add_line)
self.BtnConferma = wx.Button(self.Panel, 12, "Conferma", pos=(130,38))
self.list_ctrl = wx.ListCtrl(self.Panel, pos=(10,90),size=(-1,330),style=wx.LC_REPORT|wx.BORDER_SUNKEN)
self.list_ctrl.InsertColumn(0, 'Name')
self.list_ctrl.InsertColumn(1, 'Start')
self.list_ctrl.InsertColumn(2, 'Finish', width=100)
wx.Button(self.Panel, 22, "Exit", pos=wx.Point(470,400))
self.Bind(wx.EVT_BUTTON, self.close, id=22)
self.Bind(wx.EVT_BUTTON, self.add_line, self.BtnConferma, id=12)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.list_ctrl, 0, wx.ALL|wx.EXPAND, 5)
sizer.Add(self.BtnConferma, 0, wx.ALL|wx.CENTER, 5)
self.led = gizmos.LEDNumberCtrl(self.Panel, -1, pos = (350,25), size = (200,50), style = gizmos.LED_ALIGN_CENTER)
self.led.SetBackgroundColour("#c0c0c0")
self.led.SetForegroundColour("black")
self.OnTimer(None)
self.timer = wx.Timer(self, -1)
self.timer.Start(1000)
self.Bind(wx.EVT_TIMER, self.OnTimer)
style = gizmos.LED_ALIGN_CENTER
def OnTimer(self, event):
current = time.localtime(time.time())
self.ts = time.strftime("%H:%M:%S", current)
self.led.SetValue(self.ts)
if self.ts in self.ceck:
self.list_ctrl.SetItemTextColour(self.ceck.get(self.ts), wx.WHITE)
self.list_ctrl.SetItemBackgroundColour(self.ceck.pop(self.ts), wx.RED)
def add_line(self,event):
val = str(self.CTesto.GetValue())
if val== '':
msg = wx.MessageDialog(self, "Error", "Error", wx.OK| wx.ICON_ERROR)
msg.ShowModal()
msg.Destroy()
else:
if self.list_ctrl.GetItemCount() == 10:
for i in range(7):
d = self.list_ctrl.GetItem(0,2)
del_text = d.GetText()
#remove the dictionary values for the items being deleted
try: # It may already have been popped from the dict if the colour was changed
self.ceck.pop(del_text)
except:
pass
self.list_ctrl.DeleteItem(0)
self.index -= 1
#reset the dictionary vales for the existing ctrl items they have new index values
new_idx = 0
for i in range (3):
item = self.list_ctrl.GetItemText(i,2)
self.ceck[item] = new_idx
new_idx += 1
dataCorrente = datetime.datetime.now()
oraAttuale =(dataCorrente.strftime("%H:%M:%S"))
plus = (datetime.datetime.strptime(oraAttuale, "%H:%M:%S") + datetime.timedelta(minutes=1))
global plus2
plus2 = plus.strftime("%H:%M:%S")
if plus2 in self.ceck:
msg = wx.MessageDialog(self, "Duplicate Time", "Error", wx.OK| wx.ICON_ERROR)
msg.ShowModal()
msg.Destroy()
return
self.list_ctrl.InsertItem(self.index, val)
self.list_ctrl.SetItem(self.index, 1, oraAttuale)
self.list_ctrl.SetItem(self.index, 2, str(plus2))
self.index += 1
InsVal = (val + " - " + oraAttuale + " - " + plus2 + '\n')
self.CTesto.Clear()
self.ceck[plus2] = self.index -1
def close(self,event):
hDialog=wx.MessageDialog(self, "°°°", "Exit", wx.OK|wx.CANCEL| wx.ICON_EXCLAMATION)
rispostaDialog=hDialog.ShowModal()
hDialog.Destroy()
if rispostaDialog == wx.ID_OK:
self.Destroy()
app = wx.App()
frame = CWindow(None, -1, "Example")
frame.Show()
frame.Center()
app.MainLoop()

How can I stream program output to wxpython listctrl?

I'm making project for school, which is temperature measuring platform with raspberry pi and i'm trying it to stream my data continuous into GUI. Please help.
I have a problem with putting output to wxListCtrl.
This is my code:
import spidev
import time
import math
from time import strftime
import string
import os
spi = spidev.SpiDev()
spi.open(0, 0)
filename = strftime("%d-%b-%Y %H_%M_%S")
def read_adc(adcnum):
# read SPI data from MCP3304 chip, 8 possible adc's (0 thru 7)
if adcnum > 7 or adcnum < 0:
return -1
# Frame format: 0000 1SCC | C000 000 | 000 000
r = spi.xfer2([((adcnum & 6) >> 1)+12 , (adcnum & 1) << 7, 0])
adcout = ((r[1] & 15) << 8) + r[2]
return adcout
def make_sure_path_exists(path):
try:
os.makedirs(path)
except OSError:
if not os.path.isdir(path):
raise
def get_temperature(adc):
# read thermistor voltage drop and convert it to degrees of Celsius
value = read_adc(adc) #read the adc
volts = (value * 3.3) / 4095 #calculate the voltage
# check if the thermistor is connected to this channel
if volts > 3.2:
return 0
ohms = (volts*10000)/(3.3-volts) #calculate thermistor resistance
lnohm = math.log1p(ohms) #take ln(ohms)
# a, b, & c values from www.rusefi.com/Steinhart-Hart.html
# 0-50 C
a = 0.001125256672
b = 0.0002347204473
c = 0.00000008563052732
# Steinhart Hart Equation
# T = 1/(a + b[ln(ohm)] + c[ln(ohm)]^3)
t1 = (b*lnohm) #b[ln(ohm)]
c2 = lnohm #c[ln(ohm)]
t2 = c*math.pow(c2,3) #c[ln(ohm)]^3
temp = 1/(a + t1 + t2) #calcualte temperature in K
tempc = temp - 273.15 #K to C
#print out info
#print ("%4d/4095 => %5.4f V => %6.1f ? => %5.2f °K => %3.1f °C from adc %d" % (value, volts, ohms, temp, tempc, adc))
print ("%3.1f °C from sensor %d" % (tempc, adc))
return tempc
make_sure_path_exists("./data")
'''while True:
#write to log
log = open("./data/"+filename+'.csv', 'a') #open a text file for logging
log.write(strftime("%d/%m/%y,%H:%M:%S"))
for x in range (0,8):
log.write(",%3.1f" % (get_temperature(x)))
log.write(strftime("\n"))
log.close()
time.sleep(5)'''
class Myframe(wx.Frame):
def Close(self, event):
dialog=wx.MessageDialog(self, 'For sure?', 'End work', style=wx.OK | wx.CANCEL)
x=dialog.ShowModal()
dialog.Destroy()
if x == wx.ID_OK:
self.Close()
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Temperature Monitoring", size=(1024,760))
panel = wx.Panel(self, wx.ID_ANY)
self.index = 0
MenuListwa=wx.MenuBar()
ProgMenu=wx.Menu()
ProgMenuItem1=ProgMenu.Append(wx.ID_ANY,'Temperature','Read data')
self.Bind(wx.EVT_MENU, self.OpenData, ProgMenuItem1)
MenuListwa.Append(ProgMenu,'Data')
ProgMenu=wx.Menu()
ProgMenuItem1=ProgMenu.Append(wx.ID_EXIT, 'End', 'End program')
MenuListwa.Append(ProgMenu, 'Exit')
self.Bind(wx.EVT_MENU, self.Close, ProgMenuItem1)
self.SetMenuBar(MenuListwa)
self.list_ctrl = wx.ListCtrl(panel, size=(-1,600),
style=wx.LC_REPORT
|wx.BORDER_SUNKEN
)
self.list_ctrl.InsertColumn(0, 'Record', width=100)
self.list_ctrl.InsertColumn(1, 'Temperature', width=800)
btn = wx.Button(panel, label='Add record')
btn.Bind(wx.EVT_BUTTON, self.onStartTimer)
self.timer = wx.Timer(self, wx.ID_ANY)
self.Bind(wx.EVT_TIMER, self.add_records, self.timer)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.list_ctrl, 0, wx.ALL|wx.EXPAND, 5)
sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)
panel.SetSizer(sizer)
def onStartTimer(self, event):
print 'rekordy'
self.timer.Start(10)
def add_records(self, event):
while True:
Temp=[]
for ch in range(0,8):
Temp.append(get_temperature(ch))
line = "Record %s" % self.index
self.list_ctrl.InsertStringItem(self.index, line)
add1 = self.list_ctrl.SetStringItem(self.index, 1, Temp[self.index])
for i in Temp:
add1 += self.list_ctrl.SetStringItem(self.index, 1, Temp[self.index])
self.index += 1
time.sleep(30)
# Run
if __name__ == "__main__":
app = wx.App(False)
frame = Myframe()
frame.Show()
frame.Update()
app.MainLoop()
snippet:
def onStartTimer(self, event):
print 'records'
self.timer.Start(10)
time.sleep(10)
def add_record(self, event):
while True:
for ch in range(0,8):
Temp.append(get_temperature(ch))
line = "Record %s" % self.index
self.list_ctrl.InsertStringItem(self.index, line)
add1 = self.list_ctrl.SetStringItem(self.index, 1, str(Temp[self.index]))
for i in Temp:
add1 += self.list_ctrl.SetStringItem(self.index, 1, str(Temp[self.index]))
self.index += 1
you need to create a wx.Timer and bind it to an event that will update your list control, add this to the end of the frame's init method
TIMER_ID = wx.NewId()
self.timer = wx.Timer(id=TIMER_ID)
self.Bind(wx.EVT_TIMER, self.on_timer, id=TIMER_ID)
self.timer.Start(10*1000)
def on_timer(self, event):
self.add_records()
def add_records(self):
for ch in range(0, 8):
temp = get_temperature(ch)
line = "Record %s" % self.index
self.list_ctrl.InsertStringItem(self.index, line)
self.list_ctrl.SetStringItem(self.index, 1, temp)
self.index += 1

(MainWindow) Object has no attribute (go) [WxPython]

I'm working on making a bind event on a button refer to a function, however i get the error explained in the title.
I already have another bind event working and coded, and as far as i can tell there is zero difference between the two syntactically.
def OnBtnSuperTesting(self, event):
class MainWindow(wx.Frame):
def updateList(self, e):
#########Defining some listbox possibilites
T89 = [large array was here]
T87AZ = [large array was here]
T89ZA = T89AZ[::-1]
T87ZA = T87AZ[::-1]
#############
if self.radioAtoZ.GetValue() == True:
if self.radioT89.GetValue() == True:
choices = T89AZ
else:
choices = T87AZ
elif self.radioZtoA.GetValue() == True:
if self.radioT89.GetValue() == True:
choices = T89ZA
else:
choices = T87ZA
else:
if self.radioT89.GetValue() == True:
choices = T89
else:
choices = T87
self.listbox.Set(choices)
def Generate(self, e):
#probably need a try except here
selection = self.listbox.GetString(self.listbox.GetSelection())
if self.radioT89 == True:
if selection == 'String name here':
self.pathname = 'pathname here (its coded)'
#Assume the indentation here is right, StackOverflow isn't fommating this nicely
self.lstCommands.AppendRows(1, 1)
item = self.lstCommands.GetNumberRows()-1
self.lstCommands.SetCellValue(item, 0, "Add Module")
self.lstCommands.SetCellValue(item, 1, self.pathname)
self.modifiedFlg = True
def __init__(self, parent, title):
self.dirname=''
wx.Frame.__init__(self, parent, title=title, size=(320,440))
self.SetBackgroundColour(wx.WHITE)
self.CenterOnScreen()
self.CreateStatusBar()
self.radioT89 = wx.RadioButton(self, -1, 'T89 only', pos = (2,0), style = wx.RB_GROUP)
self.radioT87 = wx.RadioButton(self, -1, 'T87 only', pos = (154, 0))
self.radioKeySort = wx.RadioButton(self, -1, 'Sort by Key', pos = (2,40), style = wx.RB_GROUP)
self.radioAtoZ = wx.RadioButton(self, -1, 'Sort Name A-Z', pos = (2,60))
self.radioZtoA = wx.RadioButton(self, -1, 'Sort Name Z-A', pos = (2,80))
self.checkCode = wx.CheckBox(self, -1, 'Generate Code', pos = (154,40))
self.checkBuild = wx.CheckBox(self, -1, 'Generate Build Report', pos = (154, 60))
self.ln = wx.StaticLine(self, -1, pos = (0,15), size = (300,3), style = wx.LI_HORIZONTAL)
self.ln2 = wx.StaticLine(self, -1, pos = (150,15), size = (3,100), style = wx.LI_VERTICAL)
self.radioT87.Bind(wx.EVT_RADIOBUTTON, self.updateList)
self.radioT89.Bind(wx.EVT_RADIOBUTTON, self.updateList)
self.radioKeySort.Bind(wx.EVT_RADIOBUTTON, self.updateList)
self.radioAtoZ.Bind(wx.EVT_RADIOBUTTON, self.updateList)
self.radioZtoA.Bind(wx.EVT_RADIOBUTTON, self.updateList)
self.go.Bind(wx.EVT_BUTTON, self.Generate)
self.go = wx.Button(self,-1, label = 'Go!', pos = (110, 325))
# Setting up the menu.
filemenu= wx.Menu()
menuAbout= filemenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
menuExit = filemenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
# Creating the menubar.
menuBar = wx.MenuBar()
menuBar.Append(filemenu,"&File")
self.SetMenuBar(menuBar)
# Events.
self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
self.SetAutoLayout(1)
self.Show()
def OnExit(self,e):
self.Close(True) # Close the frame.
app = wx.App(False)
frame = MainWindow(None, "Supervisory Testing")
app.MainLoop()
So, you can see that the def updateList is indented the same as def Generate. It also has the same parameters and the same bind event syntax, with the exception that one is a radio button and the other is a button. What am i doing wrong?
You are binding to self.go in the line before you have asigned wx.Button to self.go, move the bind to after the button is created.

wxPython - dynamially update a listctrl depending on input into a textctrl

does anyone of you have an example how to make the following possible:
I have a listctrl that displays > 600 items. Now I need to search in these items for a text the user inputs and update the list to only show the items containing this string.
So let us say the list contains "Hello", "Hi" and "Morning". The list displays all three items. Now the user types "h" into the textctrl, and the listctrl is narrowed down to "Hello" and "Hi". If the user instead types "o", and the list becomes "Hello" and "Morning".
Is this possible? Or is there any other convenient way to find an item in a listctrl? The build in "find as you type" is only of real use if you do exactly know what you search for - and in my case this will not really be the case...
Thanks, Woodpicker
The wxPython demo has a pretty good "type-ahead" filter built into it. Looking at the source code to Main.py they do it the "manual way", loop and rebuild the list. They are using a treeview but the ideas are sound:
def OnSearch(self, event=None):
value = self.filter.GetValue()
if not value:
self.RecreateTree()
return
wx.BeginBusyCursor()
for category, items in _treeList:
self.searchItems[category] = []
for childItem in items:
if SearchDemo(childItem, value):
self.searchItems[category].append(childItem)
wx.EndBusyCursor()
self.RecreateTree()
I like the ObjectListView wrapper better than the straight wx.ListCtrl. It includes the ability to filter items in the control as a feature of the widget. You can read about it here: http://objectlistview.sourceforge.net/python/features.html#filtering and here's the main page for the control: http://objectlistview.sourceforge.net/python/
Here is an example of filtering an UltimateListCtrl.
I know this is 2 years later but I've found other examples on stackoverflow really, really helpful.
I'm new to python/wxpython but hopefully it will be useful.
starting from http://www.blog.pythonlibrary.org/2011/11/02/wxpython-an-intro-to-the-ultimatelistctrl/
import wx
from wx.lib.agw import ultimatelistctrl as ULC
class ULC_Panel(wx.Panel):
""""""
def __init__(self, parent, col_headers=None, list_data=None, options=None, dlg=None,
selected_list=None):
"""Constructor"""
wx.Panel.__init__(self, parent)
self.options = options
self.show_only_selected = False
self.filter_string = ""
hsizer = wx.BoxSizer(wx.HORIZONTAL)
okayButton = wx.Button(self, wx.ID_OK, "OK")
okayButton.SetToolTip(wx.ToolTip("Click to close this dialog and use the selections"))
self.Bind(wx.EVT_BUTTON, self.OnOkayCanButton, okayButton)
hsizer.Add(okayButton, 0, wx.ALL, 5)
canButton = wx.Button(self, wx.ID_CANCEL, "Cancel")
canButton.SetToolTip(wx.ToolTip("Click to close this dialog and cancel selections"))
self.Bind(wx.EVT_BUTTON, self.OnOkayCanButton, canButton)
hsizer.Add(canButton, 0, wx.ALL, 5)
cb_show_only = wx.CheckBox(self, -1, "Show only selected items?")
cb_show_only.SetValue(self.show_only_selected)
cb_show_only.SetToolTip(wx.ToolTip("Click to show only selected rows"))
self.Bind(wx.EVT_CHECKBOX, self.EvtShowOnly, cb_show_only)
hsizer.Add(cb_show_only, 0, wx.ALL, 5)
self.stext = wx.StaticText(self, -1, "Filter: ", style=wx.ALIGN_LEFT)
self.filtr = wx.TextCtrl(self, -1, "", style=wx.ALIGN_LEFT)
self.Bind(wx.EVT_TEXT, self.OnFiltr, self.filtr)
fsizer = wx.BoxSizer(wx.HORIZONTAL)
fsizer.Add(self.stext, 0, wx.ALL)
fsizer.Add(self.filtr, 1, wx.EXPAND)
font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
boldfont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
boldfont.SetWeight(wx.BOLD)
boldfont.SetPointSize(12)
self.ultimateList = ULC.UltimateListCtrl(self, agwStyle = wx.LC_REPORT
| wx.LC_VRULES | ULC.ULC_HAS_VARIABLE_ROW_HEIGHT
| wx.LC_HRULES)
self.checkbox = [None] * len(list_data)
if selected_list != None:
self.selected = selected_list
else:
self.selected = [False] * len(list_data)
self.rows_max = len(list_data)
self.rows_current = -1
self.cols_max = len(col_headers)
self.cols_extra = 1
if options & ULC.ULC_MASK_CHECK:
self.cols_extra += 1
for i in xrange(self.cols_max+self.cols_extra):
info = ULC.UltimateListItem()
info._mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT
info._image = []
info._format = 0
info._kind = 1
width = 150
if i >= self.cols_extra:
info._text = col_headers[i-self.cols_extra]
elif i == 0:
info._text = "Row"
width = 35
elif i == 1 and options & ULC.ULC_MASK_CHECK:
info._text = "Select"
width = 50
self.ultimateList.InsertColumnInfo(i, info)
self.ultimateList.SetColumnWidth(i, width)
self.list_data = list_data
pos = self.populate_table("")
if pos != None:
self.sz = self.ultimateList.GetItemRect(pos)
self.width = self.sz[2] + self.sz[3]
self.height = self.sz[1]
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(hsizer, 0, wx.EXPAND)
sizer.Add(fsizer, 0, wx.EXPAND)
sizer.Add(self.ultimateList, 1, flag=wx.EXPAND)
self.SetSizer(sizer)
sizer.Fit(self)
def EvtShowOnly(self, event):
cb = event.GetEventObject()
val = cb.GetValue()
self.show_only_selected = val
pos = self.populate_table(self.filter_string)
print "show_only_selected val= ", val
def EvtCheckBox(self, event):
cb = event.GetEventObject()
id = event.GetId()
val = cb.GetValue()
self.selected[id] = val
print "id, val= ", id, val
def OnOkayCanButton(self, event):
id = event.GetId()
dlg.EndModal(id)
def myGetNeedWH(self):
return (self.width, self.height)
def myGetSelectedState(self):
return self.selected
def populate_table(self, str_in):
busy = wx.BusyCursor()
if str_in:
str_low = str_in.lower()
if self.options & ULC.ULC_MASK_CHECK:
# if we have widgets in the row then we have to delete 1 row
# at a time (or else it leaves some of the widgets)
i = self.rows_current
#print "i, self.rows_max= ", i, self.rows_max
while i >= 0:
#print "i= ", i
self.ultimateList.DeleteItem(i)
i -= 1
else:
self.ultimateList.DeleteAllItems()
row = -1
for i in xrange(len(self.list_data)):
tlwr = self.list_data[i][0].lower()
if not str_in or tlwr.find(str_low) >= 0:
if self.show_only_selected and self.selected[i] == False:
continue
row += 1
for j in xrange(self.cols_max+self.cols_extra):
if j == 0:
pos = self.ultimateList.InsertStringItem(row, str(row))
elif j == 1 and self.options & ULC.ULC_MASK_CHECK:
self.checkbox[i] = wx.CheckBox(self.ultimateList, id= i)
self.checkbox[i].SetValue(self.selected[i])
self.checkbox[i].SetToolTip(wx.ToolTip("Click to select this row"))
self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, self.checkbox[i])
self.ultimateList.SetItemWindow(pos, col=1, wnd=self.checkbox[i], expand=False)
else:
self.ultimateList.SetStringItem(row, j, self.list_data[i][j-self.cols_extra])
self.rows_current = row
return row
def OnFiltr(self, event):
str1 = event.GetString()
id = event.GetId()
#print "got txt_tval str[%s]= %s" % (id, str1)
self.filter_string = str1
pos = self.populate_table(str1)
event.Skip()
return
########################################################################
class FilterListDiag(wx.Dialog):
def __init__(self, parent, id, title, headers=None, data_table=None, options=None, selected_list=None):
wx.Dialog.__init__(self, parent, id, title="", style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
options_in = options
self.panel = ULC_Panel(self, col_headers=headers, list_data=data_table, options=options_in,
dlg=self, selected_list=selected_list)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.panel, 1, wx.EXPAND)
self.SetSizer(sizer)
(self.width, self.height) = self.panel.myGetNeedWH()
def myGetNeedWH(self):
return (self.width, self.height)
def myGetSelectedState(self):
return self.panel.myGetSelectedState()
class TestFrame(wx.Frame):
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title="MvP UltimateListCtrl Demo", size=(850,600))
#----------------------------------------------------------------------
if __name__ == "__main__":
app = wx.App(False)
frame = TestFrame()
col_headers = ['col0', 'col1', 'col2']
list_data = [
["Newsboys", "Go", "Rock"],
["Puffy", "Bring It!", "Pop"],
["Family Force 5", "III", "Pop"],
["Me2", "III", "Pop"],
["Duffy", "III", "Pop"],
["Fluffy", "III", "Pop"],
]
# sel_data passes in a list of which rows are already selected
sel_data = [
False,
False,
False,
False,
True,
False,
]
opt=ULC.ULC_MASK_CHECK # just reusing this to indicate I want a column of checkboxes.
dlg = FilterListDiag(frame, -1, "hi", headers=col_headers, data_table=list_data, options=opt, selected_list=sel_data)
(w, h) = dlg.myGetNeedWH()
print w,h
dlg.SetSizeWH(w, 300)
val = dlg.ShowModal()
selected = dlg.myGetSelectedState()
print "okay, can, val= ", wx.ID_OK, wx.ID_CANCEL, val
dlg.Destroy()
print 'selected=', selected
I have something different.
I created a dictionary and updated every time there is an entry in the list ctrl. Now, when I have a search box, which changes the list ctrl with each input from the keyboard and I clear and re-update my dictionary. This way, I always have the latest index for the values.
Code is as below:
class ViewUserDialog(wx.Dialog):
def __init__(self):
title = 'View Users Records'
super().__init__(parent=None, size=(750, 600), title=title)
self.main_sizer = wx.BoxSizer(wx.VERTICAL)
self.list_sizer = wx.BoxSizer(wx.VERTICAL)
self.row_obj_dict = {}
.
.
.
self.list_ctrl_View_User.InsertColumn(0, "ID", width=150)
self.list_ctrl_View_User.InsertColumn(1, "User Name", width=150)
for index, users in original_user_frame.iterrows():
self.list_ctrl_View_User.InsertItem(indexes, user_id_value)
self.list_ctrl_View_User.SetItem(indexes, 1, users.NAME)
user_objects.append(users)
self.row_obj_dict[indexes] = users
indexes += 1
Now on searching, and selecting an item in lstctrl, you will still get your results:
def on_view(self, event):
selection = self.list_ctrl_View_User.GetFocusedItem()
self.list_ctrl_View_User.ClearAll()
if selection >= 0:
user = self.row_obj_dict[selection]
print(user)
self.list_ctrl_View_User.InsertColumn(0, "ID", width=150)
self.list_ctrl_View_User.InsertColumn(1, "User Name", width=150)
for index, users in original_user_frame.iterrows():
self.list_ctrl_View_User.InsertItem(indexes, user_id_value)
self.list_ctrl_View_User.SetItem(indexes, 1, users.NAME)
This will always give the currect selected item from the lstctrl and update the list with every input.

Categories