def Open(self, e):
openFileDialog = wx.FileDialog(
self,
"Open Log file",
"",
"",
"log files (*.mi2log) |*.mi2log| All files |*.*",
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE)
if (openFileDialog.ShowModal() == wx.ID_OK):
# print 'Selected %s' %openFileDialog.GetPath()
print 'Selected %s' % openFileDialog.Paths
try:
self.grid.ClearGrid()
# thread.start_new_thread(openFile,(openFileDialog.GetPath(),))
# t = Thread(target = self.openFile, args=(openFileDialog.GetPath(),self.selectedTypes))
t = Thread(
target=self.openFile,
args=(
openFileDialog.Paths,
self.selectedTypes))
self.progressDialog = ProgressDialog(self)
t.start()
self.progressDialog.ShowModal()
if len(openFileDialog.Paths) == 1:
self.SetTitle(openFileDialog.GetPath())
else:
self.SetTitle(
"Multiple files in " +
openFileDialog.Directory)
except e:
print "Error while opening file.", e
# if (random() > 0.5):
# self.SetupGrid(self.data1)
# else:
# self.SetupGrid(self.data2)
python类grid()的实例源码
def switch_track_sync(self, from_grid=True):
if not self.playlist:
return
if self.current_track_i >= 0:
if self.player.get_state() in {vlc.State.Playing, vlc.State.Paused}:
self.playlist[self.current_track_i]['color'] = Colors.BG_SKIPPED
if self.fade_in_out and self.player.get_state() == vlc.State.Playing:
self.fade_out_sync(self.stop_fade_speed) # Blocks thread
else:
self.playlist[self.current_track_i]['color'] = Colors.BG_PLAYED_TO_END
if self.window_exists():
self.window.grid.SetCellBackgroundColour(self.current_track_i, 0,
self.playlist[self.current_track_i]['color'])
self.window.grid.ForceRefresh() # Updates colors
if self.window_exists() and from_grid:
self.current_track_i = self.window.grid.GetSelectedRows()[0]
else:
self.current_track_i = (self.current_track_i + 1) % len(self.playlist)
self.parent.bg_player.play_sync()
self.parent.bg_pause_switch.Enable(True)
def on_c2_info(self, e):
self.menu_c2_info.Enable(False)
self.grid.ClearGrid()
self.grid_set_shape(2, 2, 100)
self.grid.SetColSize(1, 200)
self.grid.SetCellValue(0, 0, "Event Name")
self.grid.SetCellValue(1, 0, "Org Login")
self.grid_column_readonly(0)
if not self.read_c2_info():
self.c2_info = ["", ""]
self.grid.SetCellValue(0, 1, self.c2_info[0])
self.grid.SetCellValue(1, 1, self.c2_info[1])
apply_button = wx.Button(self, wx.ID_APPLY)
self.Bind(wx.EVT_BUTTON, self.on_c2_info_apply, apply_button)
self.actions_panel.Add(apply_button, 1)
self.Layout()
def on_c2_info_apply(self, e):
self.c2_info = self.grid.GetCellValue(0, 1), self.grid.GetCellValue(1, 1)
if any(map(lambda x: len(x) < 3, self.c2_info)):
self.status("Your data seems to be invalid...")
return
with open(self.c2_info_filename, 'w') as f:
f.write(' '.join(self.c2_info))
if not self.read_c2_info():
self.status("Something went wrong T_T")
return
self.menu_c2_info.Enable(True)
self.grid.ClearGrid()
self.grid_set_shape(1, 1, self.grid_no_data_width)
self.grid_column_readonly(0)
self.grid.SetCellValue(0, 0, self.grid_no_data_text)
self.actions_panel.Clear()
self.Layout()
self.status("Default credentials saved at " + self.c2_info_filename)
def _updateColAttrs(self, grid):
"""
wx.grid.Grid -> update the column attributes to add the
appropriate renderer given the column name.
Otherwise default to the default renderer.
"""
for row in range(self.GetNumberRows()):
row_highlights = self.Highlights.get(row, {})
for col in range(self.GetNumberCols()):
colname = self.GetColLabelValue(col, False)
grid.SetReadOnly(row, col, True)
grid.SetCellEditor(row, col, None)
grid.SetCellRenderer(row, col, None)
highlight_colours = row_highlights.get(colname.lower(), [(wx.WHITE, wx.BLACK)])[-1]
grid.SetCellBackgroundColour(row, col, highlight_colours[0])
grid.SetCellTextColour(row, col, highlight_colours[1])
self.ResizeRow(grid, row)
def __init__(self):
wx.Frame.__init__(self, None, title="Tutorial")
self.eventDict = {}
evt_names = [x for x in dir(wx) if x.startswith("EVT_")]
for name in evt_names:
evt = getattr(wx, name)
if isinstance(evt, wx.PyEventBinder):
self.eventDict[evt.typeId] = name
grid_evt_names = [x for x in dir(wx.grid) if x.startswith("EVT_")]
for name in grid_evt_names:
evt = getattr(wx.grid, name)
if isinstance(evt, wx.PyEventBinder):
self.eventDict[evt.typeId] = name
panel = wx.Panel(self, wx.ID_ANY)
btn = wx.Button(panel, wx.ID_ANY, "Get POS")
btn.Bind(wx.EVT_BUTTON, self.onEvent)
panel.Bind(wx.EVT_LEFT_DCLICK, self.onEvent)
panel.Bind(wx.EVT_RIGHT_DOWN, self.onEvent)
def OnInit(self):
self.res = xrc.XmlResource("grid.xrc")
frame = self.res.LoadFrame(None, 'MyFrame')
panel = xrc.XRCCTRL(frame, "MyPanel")
grid = xrc.XRCCTRL(panel, "MyGrid")
print(type(grid))
grid.CreateGrid(25, 6)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(grid, 1, wx.EXPAND|wx.ALL, 5)
panel.SetSizer(sizer)
frame.Show()
return True
def printSelectedCells(self, top_left, bottom_right):
"""
Based on code from
http://ginstrom.com/scribbles/2008/09/07/getting-the-selected-cells-from-a-wxpython-grid/
"""
cells = []
rows_start = top_left[0]
rows_end = bottom_right[0]
cols_start = top_left[1]
cols_end = bottom_right[1]
rows = range(rows_start, rows_end+1)
cols = range(cols_start, cols_end+1)
cells.extend([(row, col)
for row in rows
for col in cols])
print("You selected the following cells: ", cells)
for cell in cells:
row, col = cell
print(self.myGrid.GetCellValue(row, col))
def AppendCols(self, numCols=1):
# for part in self._OM.list('part', self.partitionuid):
# print '\nparts1', part.uid
for i in range(numCols):
prop = self._OM.new('property')
prop.defaultdata = np.nan
# for part in self.partuid:
# self._OM.add(prop, part)
# print '\nparts2', self.partuid
self._OM.add(prop, self.partitionuid)
self.propmap.append(prop.uid)
self.GetView().BeginBatch()
msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_NOTIFY_COLS_APPENDED, numCols)
self.GetView().ProcessTableMessage(msg)
self.GetView().EndBatch()
return True
def GetAttr(self, row, col, kind):
#if _iswxphoenix:
attr = wx.grid.GridCellAttr().Clone()
#else:
# attr = wx.grid.GridCellAttr()
if col >= self.N_COLS:
attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
elif col == 0:
attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
elif col == 1:
part = self._OM.get(self.partmap[row])
attr.SetBackgroundColour(part.color)
attr.SetReadOnly(True)
elif col == 2:
attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
elif col == 3:
attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
return attr
def on_cell_dlclick(self, event):
if event.GetCol() == 1:
row = event.GetRow()
table = self.tables[self.currentwellindex][self.currentpartitionindex]
color = table.get_color(row)
global COLOUR_DATA
COLOUR_DATA.SetColour(color)
dlg = wx.ColourDialog(self, COLOUR_DATA)
if dlg.ShowModal() == wx.ID_OK:
COLOUR_DATA = dlg.GetColourData()
color = COLOUR_DATA.GetColour().Get(True)
# TODO: alpha
table.set_color(row, color)
self.grid.ForceRefresh()
dlg.Destroy()
else:
event.Skip()
def AppendRows(self, numRows=1):
rocktype = self.GrainEntry()
# rocktype = self._OM.new('rocktype')
rocktype.defaultdata = np.nan
self._OM.add(rocktype, self.rocktableuid)
self.rocktypemap.append(rocktype.uid)
color = self.get_color(0)
self.set_color(-1,color)
self.GetView().BeginBatch()
msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED, numRows)
self.GetView().ProcessTableMessage(msg)
self.GetView().EndBatch()
return True
def GetAttr(self, row, col, kind):
#if _iswxphoenix:
attr = wx.grid.GridCellAttr().Clone()
if col >= self.N_COLS:
attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
elif col == 0:
attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
elif col == 1:
rocktype = self._OM.get(self.rocktypemap[row])
attr.SetBackgroundColour(rocktype.color)
attr.SetReadOnly(True)
elif col == 2:
attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
elif col == 3:
attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
return attr
def on_cell_dlclick(self, event):
if event.GetCol() == 1:
row = event.GetRow()
table = self.tables[self.currentwellindex][self.currentrocktableindex]
color = table.get_color(row)
global COLOUR_DATA
COLOUR_DATA.SetColour(color)
dlg = wx.ColourDialog(self, COLOUR_DATA)
if dlg.ShowModal() == wx.ID_OK:
COLOUR_DATA = dlg.GetColourData()
color = COLOUR_DATA.GetColour().Get(True)
# TODO: alpha
table.set_color(row, color)
self.grid.ForceRefresh()
dlg.Destroy()
else:
event.Skip()
def load_playlist_to_grid(self):
if self.window.grid.GetNumberRows() > 0:
self.window.grid.DeleteRows(0, self.window.grid.GetNumberRows(), False)
self.window.grid.AppendRows(len(self.playlist))
for i in range(len(self.playlist)):
self.window.grid.SetCellValue(i, 0, self.playlist[i]['title'])
self.window.grid.SetReadOnly(i, 0)
self.window.grid.SetCellBackgroundColour(i, 0, self.playlist[i]['color'])
self.window.grid.AutoSize()
self.window.Layout()
self.window.play_btn.Enable(True)
player_state = self.parent.bg_player.player.get_state()
if player_state in range(5): # If playing
self.window.pause_btn.SetValue(player_state == vlc.State.Paused)
def play_sync(self):
self.player.set_media(self.vlc_instance.media_new(self.playlist[self.current_track_i]['path']))
if self.player.play() != 0: # [Play] button is pushed here!
wx.CallAfter(lambda: self.parent.set_bg_player_status("Playback FAILED !!!"))
return
state = self.player.get_state()
start = time.time()
while state != vlc.State.Playing:
state = self.player.get_state()
status = "%s [%fs]" % (self.parent.player_state_parse(state), (time.time() - start))
wx.CallAfter(lambda: self.parent.set_bg_player_status(status))
time.sleep(0.005)
self.playlist[self.current_track_i]['color'] = Colors.BG_PLAYING_NOW
if self.window_exists():
def ui_upd():
self.window.pause_btn.Enable(True)
self.window.lock_btn.Enable(True)
self.window.grid.SetCellBackgroundColour(self.current_track_i, 0, Colors.BG_PLAYING_NOW)
self.window.grid.ForceRefresh() # Updates colors
self.window.pause_btn.SetValue(False)
wx.CallAfter(ui_upd)
volume = 0 if self.fade_in_out else self.volume
start = time.time()
while self.player.audio_get_volume() != volume:
self.player.audio_set_mute(False)
self.player.audio_set_volume(volume)
status = "Trying to unmute... [%fs]" % (time.time() - start)
wx.CallAfter(lambda: self.parent.set_bg_player_status(status))
time.sleep(0.005)
if self.fade_in_out:
self.fade_in_sync(self.stop_fade_speed)
wx.CallAfter(lambda: self.parent.set_bg_player_status("%s Vol:%d" %
(self.parent.player_state_parse(self.player.get_state()),
self.player.audio_get_volume())))
def SetupGrid(self):
self.min_time = datetime.strptime("3000 Jan 1", '%Y %b %d')
self.max_time = datetime.strptime("1900 Jan 1", '%Y %b %d')
n = len(self.data_view)
# self.grid.CreateGrid(max(25, n), 2)
if n > self.grid.GetNumberRows():
self.grid.InsertRows(0, n - self.grid.GetNumberRows())
else:
self.grid.DeleteRows(0, self.grid.GetNumberRows() - n)
self.grid.ClearGrid()
self.grid.SetColLabelValue(0, "Timestamp")
self.grid.SetColLabelValue(1, "Type ID")
for i in range(n):
try:
cur_time = datetime.strptime(
self.data_view[i]["Timestamp"],
'%Y-%m-%d %H:%M:%S.%f')
except Exception as e:
cur_time = datetime.strptime(
self.data_view[i]["Timestamp"], '%Y-%m-%d %H:%M:%S')
self.min_time = min(self.min_time, cur_time)
self.max_time = max(self.max_time, cur_time)
self.grid.SetCellValue(i, 0, str(self.data_view[i]["Timestamp"]))
self.grid.SetCellValue(i, 1, str(self.data_view[i]["TypeID"]))
self.grid.SetReadOnly(i, 0)
self.grid.SetReadOnly(i, 1)
#self.grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.onRowClick)
def grid_set_shape(self, new_rows, new_cols, default_col_size=None):
current_rows, current_cols = self.grid.GetNumberRows(), self.grid.GetNumberCols()
if new_rows < current_rows:
self.grid.DeleteRows(0, current_rows - new_rows, True)
if new_cols < current_cols:
self.grid.DeleteCols(0, current_cols - new_cols, True)
if new_rows > current_rows:
self.grid.AppendRows(new_rows - current_rows)
if new_cols > current_cols:
self.grid.AppendCols(new_cols - current_cols)
if default_col_size:
map(lambda col: self.grid.SetColSize(col, default_col_size), range(new_cols))
def grid_column_readonly(self, col):
grid_disabled_color = wx.Colour(240, 240, 240)
def disable_cell(cell):
self.grid.SetReadOnly(*cell)
self.grid.SetCellBackgroundColour(*(cell + (grid_disabled_color,)))
map(disable_cell, [(row, col) for row in range(self.grid.GetNumberRows())])
# ------------------ Cosplay2 ------------------
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "Simple Grid Demo", size=(640,480))
self.grid = SimpleGrid(self)
def __init__(self, parent, data, colnames):
# The base class must be initialized *first*
wx.grid.PyGridTableBase.__init__(self)
self.data = data
self.colnames = colnames
self.Highlights = {}
self.Parent = parent
# XXX
# we need to store the row length and collength to
# see if the table has changed size
self._rows = self.GetNumberRows()
self._cols = self.GetNumberCols()
def ResetView(self, grid):
"""
(wx.grid.Grid) -> Reset the grid view. Call this to
update the grid if rows and columns have been added or deleted
"""
grid.CloseEditControl()
grid.BeginBatch()
for current, new, delmsg, addmsg in [
(self._rows, self.GetNumberRows(), wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED, wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED),
(self._cols, self.GetNumberCols(), wx.grid.GRIDTABLE_NOTIFY_COLS_DELETED, wx.grid.GRIDTABLE_NOTIFY_COLS_APPENDED),
]:
if new < current:
msg = wx.grid.GridTableMessage(self, delmsg, new, current-new)
grid.ProcessTableMessage(msg)
elif new > current:
msg = wx.grid.GridTableMessage(self, addmsg, new-current)
grid.ProcessTableMessage(msg)
self.UpdateValues(grid)
grid.EndBatch()
self._rows = self.GetNumberRows()
self._cols = self.GetNumberCols()
# update the column rendering scheme
self._updateColAttrs(grid)
# update the scrollbars and the displayed part of the grid
grid.AdjustScrollbars()
grid.ForceRefresh()
def UpdateValues(self, grid):
"""Update all displayed values"""
# This sends an event to the grid table to update all of the values
msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
grid.ProcessTableMessage(msg)
def SetFocus(self):
if self:
wx.grid.Grid.SetFocus(self)
def _updateColAttrs(self, grid):
"""
wx.grid.Grid -> update the column attributes to add the
appropriate renderer given the column name.
Otherwise default to the default renderer.
"""
for row in range(self.GetNumberRows()):
row_highlights = self.Highlights.get(row, {})
for col in range(self.GetNumberCols()):
editor = None
renderer = None
colname = self.GetColLabelValue(col, False)
if col != 0:
grid.SetReadOnly(row, col, False)
if colname == "Name":
editor = wx.grid.GridCellTextEditor()
renderer = wx.grid.GridCellStringRenderer()
elif colname == "Initial Value":
editor = wx.grid.GridCellTextEditor()
renderer = wx.grid.GridCellStringRenderer()
elif colname == "Type":
editor = wx.grid.GridCellTextEditor()
else:
grid.SetReadOnly(row, col, True)
grid.SetCellEditor(row, col, editor)
grid.SetCellRenderer(row, col, renderer)
highlight_colours = row_highlights.get(colname.lower(), [(wx.WHITE, wx.BLACK)])[-1]
grid.SetCellBackgroundColour(row, col, highlight_colours[0])
grid.SetCellTextColour(row, col, highlight_colours[1])
self.ResizeRow(grid, row)
def SingleCellEditor(*x):
return wx.grid.GridCellChoiceEditor()
def _updateColAttrs(self, grid):
"""
wxGrid -> update the column attributes to add the
appropriate renderer given the column name.
Otherwise default to the default renderer.
"""
typelist = None
accesslist = None
for row in range(self.GetNumberRows()):
for col in range(self.GetNumberCols()):
editor = None
renderer = None
colname = self.GetColLabelValue(col, False)
if colname in ["Name", "Initial", "Description", "OnChange", "Options"]:
editor = wx.grid.GridCellTextEditor()
elif colname == "Class":
editor = wx.grid.GridCellChoiceEditor()
editor.SetParameters("input,memory,output")
elif colname == "Type":
pass
else:
grid.SetReadOnly(row, col, True)
grid.SetCellEditor(row, col, editor)
grid.SetCellRenderer(row, col, renderer)
grid.SetCellBackgroundColour(row, col, wx.WHITE)
self.ResizeRow(grid, row)
def __init__(self, data, colLabels=None, rowLabels=None):
wx.grid.GridTableBase.__init__(self)
self.data = data # data is stored as a list of list
self.rowLabels = rowLabels
self.colLabels = colLabels
def __init__(self, parent, title, data, cols=None, rows=None):
wx.Frame.__init__(self, parent, -1, title)
logopath = os.path.join(root_dir, 'data/logo.ico')
self.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_3DLIGHT ) )
self.SetIcon(wx.Icon(logopath, wx.BITMAP_TYPE_ICO))
TableLogManager.add(title, self)
self.data, self.cols, self.rows = data, cols, rows
tableBase = GenericTable(data, cols, rows)
self.grid = wx.grid.Grid(self)
## create tablegrid and set tablegrid value
#self.grid.SetTable(tableBase)
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.grid.CreateGrid(len(data), len(data[0]))
if cols!=None:
for i in range(len(cols)):
self.grid.SetColLabelValue(i, cols[i])
if rows!=None:
for i in range(len(rows)):
self.grid.SetColLabelValue(i, rows[i])
for i in range(len(data)):
for j in range(len(data[0])):
self.grid.SetCellValue(i, j,str(data[i][j]))
self.grid.AutoSize()
## create menus
menus = [('File(&F)',
[('Save as tab', self.OnSaveTab),
('Save as csv', self.OnSaveCsv),
('-'),
('Exit', self.OnClose)
]
),
('Help(&H)',
[('About', self.OnAbout)]
)
]
## bind the menus with the correspond events
menuBar=wx.MenuBar()
for menu in menus:
m = wx.Menu()
for item in menu[1]:
if item[0]=='-':
m.AppendSeparator()
else:
i = m.Append(-1, item[0])
if item[1]!=None:
self.Bind(wx.EVT_MENU,item[1], i)
menuBar.Append(m,menu[0])
self.SetMenuBar(menuBar)
self.Fit()
def OnMenu_Exit(self,event):
#print "grid closs"
self.Close()
event.Skip()