wxPython以关闭为中心按钮和应用程序崩溃

时间:2012-08-02 17:14:44

标签: python wxpython

有人可以帮我一石二鸟吗?我一直试图将我的wxPanel中的一个按钮居中一段时间​​,似乎无法弄明白。我尝试过不同的属性,例如wx.CENTERwx.ALIGN_CENTER以及wx.ALIGN_CENTER_HORIZONTAL,但似乎无法将按钮移动到面板的中心。我尝试居中的按钮是set_button方法中的add_unit_pane

此外,当我单击X按钮关闭程序时,程序崩溃。我没有正确处理关闭事件吗?

有人能指出我错在哪里吗?

import wx

class Example(wx.Frame):

    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        self.init_ui()

    def init_ui(self):
        self.Bind(wx.EVT_CLOSE, self.on_close_window)

        panel = wx.Panel(self)
        panel_sizer = wx.BoxSizer(wx.VERTICAL)
        panel_sizer.Add(self.add_unit_pane(panel, panel_sizer), 0, wx.EXPAND, border=5)
        panel.SetSizerAndFit(panel_sizer)

        self.Show()

    def on_close_window(self, event):
        self.Destroy()

    def add_unit_pane(self, panel, panel_sizer):
        """ Creates the Unit Measurement panel """
        unit_panel = wx.StaticBox(panel, -1, 'Unit of Measurement')
        unit_panel_sizer = wx.StaticBoxSizer(unit_panel, wx.VERTICAL)

        # Create horizontal row of widgets 1
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)

        st1 = wx.StaticText(panel, label='UNIT:')
        unit_choices = ['in (INCHES)',
                        'cm (CENTIMETERS)',
                        'mm (MILLIMETERS)'
                        ]
        unit_cb = wx.ComboBox(panel, -1, '100%',
                                     choices=unit_choices,
                                     style=wx.CB_DROPDOWN|wx.CB_READONLY)
        unit_cb.SetValue('mm (MILLIMETERS)')

        hbox1.Add(st1)
        hbox1.AddSpacer(5)
        hbox1.Add(unit_cb)

        # Create horizontal row of widgets 2
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)

        st2 = wx.StaticText(panel, label='Pixels per selected unit:')
        tc1 = wx.TextCtrl(panel)

        hbox2.Add(st2)
        hbox2.AddSpacer(5)
        hbox2.Add(tc1)

        # Create horizontal row of widgets 3
        hbox3 = wx.BoxSizer(wx.HORIZONTAL)
        set_button = wx.Button(panel, -1, 'Set')
        hbox3.Add(set_button, 0, wx.CENTER)

        # Add all other sizers to the main unit_panel_sizer
        unit_panel_sizer.Add(hbox1)
        unit_panel_sizer.AddSpacer(5)
        unit_panel_sizer.Add(hbox2)
        unit_panel_sizer.AddSpacer(5)
        unit_panel_sizer.Add(hbox3)

        # Fit all widgets to the sizer
        unit_panel.SetSizerAndFit(unit_panel_sizer)

        # Return the unit_panel_sizer
        return unit_panel_sizer

if __name__ == '__main__':
    ex = wx.App()
    Example(None, -1, "Centering Button", size=(250,150))
    ex.MainLoop()

谢谢你, 亚当

1 个答案:

答案 0 :(得分:1)

更改将hbox3添加到

的行
unit_panel_sizer.Add(hbox3,0,wx.CENTER)

也注释掉

unit_panel.SetSizerAndFit(unit_panel_sizer) 

应修复崩溃的