简体   繁体   中英

wxPython: Change Button Image

I would like to change the button image in wxPython. I am able to hide and remove the button, but when I try to add the button again to the same place, it appears in the wrong place. What am I missing?

Details: I create a class for wx.Panel. The class has a constructor. The class has two buttons. When you press the first button, the second button is hidden and then removed from the sizer. When the first button is pressed, the "clicked()" function is called. The "clicked()" function first hides the button to be removed and then removes it from the sizer. When the "clicked()" function tries to add another button to the same place as the where the second button was, the new button appears at the top of the user interface.

I would like the new button be placed to the same place as the old one. How do I do that?

class Panel(wx.Panel):

    def __init__(self, parent):

        super(Panel, self).__init__(parent)

        self.sizer = wx.GridBagSizer(11, 14)

        self.button01 = wx.Button(self, label="01")
        self.sizer.Add(self.button01, pos=(2, 0))

        self.Bind(wx.EVT_BUTTON, self.clicked, self.button01)

        self.pic = wx.Bitmap("light.jpg", wx.BITMAP_TYPE_ANY)
        self.buttonpic = wx.BitmapButton(self, -1, self.pic)
        self.sizer.Add(self.buttonpic, pos=(3, 1), flag=wx.LEFT, border=10)
        self.sizer.AddGrowableCol(2)    
        self.SetSizer(self.sizer)
        self.sizer.Fit(self)


    def clicked(self, event):

        self.sizer.Hide(   2 )
        self.sizer.Remove( 2 )

        self.pic = wx.Bitmap("dark.jpg", wx.BITMAP_TYPE_ANY)
        self.buttonpic = wx.BitmapButton(self, -1, self.pic)
        self.sizer.Add(self.buttonpic, pos=(3, 1), flag=wx.LEFT, border=10)

        event.Skip()

Edit: I had to remove a lot of code from the original code, so that StackOverflow could accept my question, so the integer given to the Hide() and Remove() functions might not be correct in this example, but the hiding and removal of the button works in the original code without errors.

Instead of creating a new widget, just call the existing button's SetBitmap method.

For those times when a new widget really is needed, be sure to call the sizer's Layout method afterwards so the sizer will redo the layout and move that widget into position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM