Sizing a frame to an image in WxPython
-
28-10-2019 - |
Pergunta
I'm making a program with an image for a backdrop, and what I'm trying to do is get the frame to fit the image precisely.
It's easy to initiate the frame with the dimensions of the image:
wx.Frame.__init__(self, parent, title=title, size=(500, 300))
but because this also accounts for the borders and header of the window, this isn't entirely accurate. Short of manually adjusting the pixel size (which wouldn't be consistent cross-OS anyway), what can I do?
Edit: I've found an answer, but it looks like I can't self-answer for a few hours. In the meantime...
Backdrop = wx.Bitmap("image.png")
self.SetClientSize((Backdrop.GetWidth(), Backdrop.GetHeight()))
Solução
You could accomplish the same thing with a sizer, which would also make things easier if you ever need to include other items alongside the image and control how they scale with the frame.
Here's a basic example of a frame that resizes itself to fit an image.
import wx
class Frame(wx.Frame):
def __init__(self, parent, id, title, img_path):
wx.Frame.__init__(self, parent, id, title,
style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER)
image = wx.StaticBitmap(self, wx.ID_ANY)
image.SetBitmap(wx.Bitmap(img_path))
sizer = wx.BoxSizer()
sizer.Add(image)
self.SetSizerAndFit(sizer)
self.Show(True)
app = wx.App()
frame = Frame(None, wx.ID_ANY, 'Image', '/path/to/file.png')
app.MainLoop()