+1 包含指向完整源代码的链接 - 使其更容易测试。
我无法在 Win32 上重现您在 wxPython 2.8.12 上描述的错误,但是在运行您的代码时,我发现在第 18 行wx.Panel
创建了一个看似无关的对象...pyed.py
self.panel = wx.Panel(self, -1)
...这似乎干扰了程序的正确运行。在注释掉那行之后,它似乎工作正常。
我注意到的其他几件事:第 56 行...
self.SetTitle("PyEd - Editing ... " + filename)
...应该放在前面的 if 块中,否则如果用户wx.FileDialog
在第 16 行和第 16 行单击“取消”,则会出现错误...
wx.Frame.__init__(self, parent, id, 'PyEd', (-1, -1), wx.Size(640, 480))
...如果您使用关键字参数而不是位置参数...
wx.Frame.__init__(self, parent=parent, id=id, title='PyEd', size=wx.Size(640, 480))
...您不必费心重新指定窗口位置的默认值,这也稍微安全一些,以防 wxPython 开发人员决定在未来版本中更改默认值。
您还可以分解常量值,并可选地创建wx.Size
对象以将该行减少到...
wx.Frame.__init__(self, parent=None, title='PyEd', size=(640, 480))
最后,关于 ID:在大多数情况下,您可能会发现它们几乎没有用处。它们派上用场的地方是您需要许多类似的控件,并且让它们由单个事件处理函数处理更有意义。
考虑这个例子......
def create_buttons(parent):
parent.button1 = wx.Button(label='Button 1')
parent.button2 = wx.Button(label='Button 2')
parent.button3 = wx.Button(label='Button 3')
parent.button1.Bind(wx.EVT_BUTTON, on_button_1)
parent.button2.Bind(wx.EVT_BUTTON, on_button_2)
parent.button3.Bind(wx.EVT_BUTTON, on_button_3)
def on_button_1(event):
print 'You clicked button 1'
def on_button_2(event):
print 'You clicked button 2'
def on_button_3(event):
print 'You clicked button 3'
...这很好,但是如果您需要 100 个按钮,您可能更愿意像这样实现它...
def create_buttons(parent):
parent.buttons = [wx.Button(id=i, label='Button %d' % i) for i in range(100)]
parent.Bind(wx.EVT_BUTTON, on_button)
def on_button(event):
button_id = event.GetId()
print 'You clicked button %d' % button_id
哦,小心id
用作变量名,因为它也是 Python 内置的函数名。