Search code examples
pythonimageuser-interfacefiremonkey

How to display Image on a Python FMX GUI App?


I've made a small Form App using the DelphiFMX GUI Library for Python, but I'm not sure how to add or display an Image onto the Form. Here's my current code:

from delphifmx import *

class frmMain(Form):
    def __init__(self, owner):
        self.Caption = 'My Form'
        self.Width = 800
        self.Height = 500

        self.imgPlay = Image(self)
        self.imgPlay.Parent = self
        self.imgPlay.Position.X = 100
        self.imgPlay.Position.Y = 100
        self.imgPlay.Width = 300
        self.imgPlay.Height = 300

def main():
    Application.Initialize()
    Application.Title = "My Application"
    Application.MainForm = frmMain(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

main()

I've tried:

self.imgPlay.Bitmap.LoadFromFile('play.png')

but the error is TypeError: "LoadFromFile" called with invalid arguments.

I've also tried:

self.imgPlay.Picture.LoadFromFile('play.png')

The error is then AttributeError: Error in getting property "Picture". Error: Unknown attribute

And lastly, I've tried simply saying:

self.imgPlay.LoadFromFile('play.png')

With a similar error AttributeError: Error in getting property "LoadFromFile". Error: Unknown attribute

What is the correct way to load an image file into the Image Component? How do I do this?


Solution

  • self.imgPlay.Bitmap.LoadFromFile('play.png') is the correct way to load an image into the component. I suspect the given file path ('play.png') doesn't exist. Something you can maybe do is get the path of the current file and then load it from that folder:

    import os
    
    ...
    
    path = os.path.dirname(os.path.abspath(__file__))
    self.imgPlay.Bitmap.LoadFromFile(path + '\play.png')
    

    Using this code works on my side: Minecraft Dirt Image showing on Python GUI App

    I'm successfully showing an Image on the Form.


    Alternatively to the Image component, there is also an ImageControl component that works similarly. Here's a code sample and screenshot using an ImageControl instead of Image:

    self.imgDirt = ImageControl(self)
    self.imgDirt.Parent = self
    self.imgDirt.Position.X = 100
    self.imgDirt.Position.Y = 100
    self.imgDirt.Width = 400
    self.imgDirt.Height = 400
    
    path = os.path.dirname(os.path.abspath(__file__))
    self.imgDirt.Bitmap.LoadFromFile(path + '\dirt.png')
    

    Python GUI App with Minecraft Dirt block image