wxPython:如何绑定按钮?

时间:2013-02-07 08:18:05

标签: binding wxpython

我刚开始使用wxPython并且遇到绑定问题。

通常,我发现绑定按钮事件的示例都是使用self.Bind(wx.EVT_BUTTON, self.OnWhatEverFunction, button)完成的。我有一个框架内部有一个面板和一个按钮,我尝试过的结果总是一个闪烁的框架,它瞬间出现,就是这样。由于代码不是那么多,我在这里附上它,希望你们中的一个能告诉我解决我的小问题的方法。

提前致谢, 托马斯

#!/usr/bin/python
import wx

class CPFSFrame(wx.Frame):
    def __init__(self, parent, title):
        super(CPFSFrame, self).__init__(parent, title=title,
                                    style = wx.BORDER | wx.CAPTION | wx.SYSTEM_MENU | wx.CLOSE_BOX,
                                    size=(350, 200))
        panel = wx.Panel(self, -1)

        pNumberLabel = wx.StaticText(panel, -1, 'Project number: ')
        pNumberText = wx.TextCtrl(panel, -1, '', size=(175, -1))
        pNumberText.SetInsertionPoint(0)

        pNameLabel = wx.StaticText(panel, -1, 'Project name: ')
        pNameText = wx.TextCtrl(panel, -1, '', size=(175, -1))
        pNameText.SetInsertionPoint(0)

        pButton = wx.Button(panel, label='Create')
        pButton.Bind(wx.EVT_BUTTON, self.OnCreate)

        sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
        sizer.AddMany([pNumberLabel, pNumberText, pNameLabel, pNameText, pButton])
        panel.SetSizer(sizer)

        statusBar = self.CreateStatusBar()

    def OnCreate(self, evt):
        self.Close(True)

        self.Centre()
        self.Show()

if __name__ == '__main__':
    app = wx.App()
    CPFSFrame(None, title='Create New Project Folder Structure')
    app.MainLoop()

1 个答案:

答案 0 :(得分:0)

您需要将“self.Show()”方法放在代码的 init 部分中。起初我以为OnCreate()正在运行,如果是,那么它会立即关闭框架,所以你什么都看不到。我会把它叫做OnClose而不是。这是一个有效的例子:

import wx

class CPFSFrame(wx.Frame):
    def __init__(self, parent, title):
        super(CPFSFrame, self).__init__(parent, title=title,
                                    style = wx.BORDER | wx.CAPTION | wx.SYSTEM_MENU | wx.CLOSE_BOX,
                                    size=(350, 200))
        panel = wx.Panel(self, -1)

        pNumberLabel = wx.StaticText(panel, -1, 'Project number: ')
        pNumberText = wx.TextCtrl(panel, -1, '', size=(175, -1))
        pNumberText.SetInsertionPoint(0)

        pNameLabel = wx.StaticText(panel, -1, 'Project name: ')
        pNameText = wx.TextCtrl(panel, -1, '', size=(175, -1))
        pNameText.SetInsertionPoint(0)

        pButton = wx.Button(panel, label='Create')
        pButton.Bind(wx.EVT_BUTTON, self.OnClose)

        sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
        sizer.AddMany([pNumberLabel, pNumberText, pNameLabel, pNameText, pButton])
        panel.SetSizer(sizer)

        statusBar = self.CreateStatusBar()
        self.Show()

    def OnClose(self, evt):
        self.Close(True)

if __name__ == '__main__':
    app = wx.App()
    CPFSFrame(None, title='Create New Project Folder Structure')
    app.MainLoop()