如何调整wxPython wx.Panel的大小?

1 投票
1 回答
5237 浏览
提问于 2025-04-16 02:47

我想在一个表单上放一个图片面板,当点击一个按钮时,最开始放在面板上的64x64的图片会被一个更大的320x224的图片替换掉。这里的像素大小并不是最重要的,关键是它们的尺寸不同。我差不多搞定了,现在两个图片都能加载,并且在点击按钮时确实会显示第二张图片——不过显示的只是第二张图片的左上角64x64的部分,而不是整个图片。

肯定可以调整面板的大小,让整个图片都能显示出来,对吧?这是我现在的代码:

#First we create our form elements. This app has a label on top of a button, both below a panel with an image on it, so we create a sizer and the elements
self.v_sizer = wx.BoxSizer(wx.VERTICAL)
self.imagePanel = wx.Panel(self, -1)
self.FileDescriptionText = wx.StaticText(self, label="No file loaded")
self.openFileDialog = wx.Button(self, label="Load a file", size=(320,40))
#Bind the button click to our press function
self.openFileDialog.Bind(wx.EVT_BUTTON, self.onOpenFileDialog)

#That done, we need to construct the form. First, put the panel, button and label in the vertical sizer...
self.v_sizer.Add(self.imagePanel, 0, flag=wx.ALIGN_CENTER)
self.v_sizer.Add(self.openFileDialog, 0, flag=wx.ALIGN_CENTER)
self.v_sizer.Add(self.ROMDescriptionText, 0, flag=wx.ALIGN_CENTER)
#then assign an image for the panel to have by default, and apply it
self.imageToLoad = wx.Image("imgs/none_loaded.png", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
self.imageCtrl = wx.StaticBitmap(self.imagePanel, -1, self.imageToLoad, (0, 0), (self.imageToLoad.GetWidth(), self.imageToLoad.GetHeight()))

#Set the sizer to be owned by the window
self.SetSizer(self.v_sizer)
#Set the current window size to the size of the sizer
self.v_sizer.Fit(self)
#Set the Minimum size of the window to the current size of the sizer
self.SetMinSize(self.v_sizer.GetMinSize())


def onOpenFileDialog(self, event):
    img = wx.Image("imgs/title.png", wx.BITMAP_TYPE_ANY)
    self.imageCtrl.SetBitmap(wx.BitmapFromImage(img))
    self.imagePanel.Refresh()

(这个方法是叫onOpenFileDialog,因为最终会从一个下拉框中选择图片。)

我该如何修改onOpenFileDialog这个方法,让它先找到图片的大小,就像在创建初始表单元素时的self.imageCtrl那一行?我找不到办法做到这一点。

1 个回答

3

试着在你的 onOpenFileDialog() 方法的最后加上 self.v_sizer.Fit(self) 这一行代码。

撰写回答