0

有人能帮我用一块石头杀死两只鸟吗?我一直试图将我的 wxPanel 中的按钮居中一段时间​​,但似乎无法弄清楚。我尝试了不同的属性,例如wx.CENTERandwx.ALIGN_CENTERwx.ALIGN_CENTER_HORIZONTAL,但似乎无法让按钮移动到面板的中心。我试图居中的按钮set_buttonadd_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()

谢谢你,亚当

4

1 回答 1

1

将添加 hbox3 的行更改为

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

也注释掉

unit_panel.SetSizerAndFit(unit_panel_sizer) 

那应该可以解决您的崩溃问题

于 2012-08-02T17:36:39.950 回答