Reputation: 33
I have created a grid using wx.grid, binding with EVT_GRID_CELL_CHANGED
to validate the user's input in a cell.
self.grid.Bind(wx.grid.EVT_GRID_CELL_CHANGED, self.OnCellChanged)
I try to create a wx.MessageBox
to pop if the input is not int
. Then I
found out the messagebox will pop up twice, which is not what I want.
The handler's code is shown below:
def OnCellChanged(self, event):
row = event.GetRow()
col = event.GetCol()
try:
cell_input = int(self.grid.GetCellValue(row, col))
except:
self.grid.SetCellValue(row, col, '')
msgbox = wx.MessageBox('Invalid Input! Please Try Again', 'Error', wx.OK | wx.ICON_HAND | wx.CENTRE)
Thanks for helping.
Upvotes: 3
Views: 2531
Reputation: 143187
It seems there is some problem with MessageBox
in function which handles event. But you can call it later using wx.CallAfter(function_name)
or wx.CallLater(miliseconds, function_name)
def OnCellChanged(self, event):
row = event.GetRow()
col = event.GetCol()
try:
cell_input = int(self.grid.GetCellValue(row, col))
except:
self.SetCellValue(row, col, '')
#wx.CallLater(100, self.Later) # time 100ms
wx.CallAfter(self.Later)
print("End OnCellChange")
def Later(self):
print("Later")
msgbox = wx.MessageBox('Invalid Input! Please Try Again', 'Error', wx.OK | wx.ICON_HAND | wx.CENTRE)
Full working example (base on example: Mouse vs Python: wxPython - An Introduction to Grids)
import wx
import wx.grid as gridlib
class MyGrid(gridlib.Grid):
def __init__(self, parent):
"""Constructor"""
gridlib.Grid.__init__(self, parent)
self.CreateGrid(12, 8)
self.Bind(gridlib.EVT_GRID_CELL_CHANGED, self.OnCellChange)
def OnCellChange(self, evt):
print("OnCellChange: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition()))
row = evt.GetRow()
col = evt.GetCol()
val = self.GetCellValue(row, col)
try:
cell_input = int(val)
except:
self.SetCellValue(row, col, '')
#wx.CallLater(100, self.Later) # time 100ms
wx.CallAfter(self.Later)
print("End OnCellChanged")
def Later(self):
print("Later")
wx.MessageBox('Invalid Input! Please Try Again', 'Error', wx.OK | wx.ICON_HAND | wx.CENTRE)
class MyForm(wx.Frame):
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, parent=None, title="An Eventful Grid")
panel = wx.Panel(self)
myGrid = MyGrid(panel)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(myGrid, 1, wx.EXPAND)
panel.SetSizer(sizer)
app = wx.App()
frame = MyForm().Show()
app.MainLoop()
Upvotes: 1