wxpython:EVT_GRID_CELL_CHANGED问题

时间:2016-12-01 08:10:50

标签: python wxpython

我使用wx.grid创建了一个网格,与EVT_GRID_CELL_CHANGED绑定以验证用户在单元格中的输入。

self.grid.Bind(wx.grid.EVT_GRID_CELL_CHANGED, self.OnCellChanged)

如果输入不是wx.MessageBox,我会尝试创建一个int来弹出。然后我 发现消息框会弹出两次,这不是我想要的。

处理程序的代码如下所示:

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)

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

似乎处理事件的函数MessageBox存在问题。但您可以稍后使用wx.CallAfter(function_name)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)

完整的工作示例(基于示例: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()