Quantcast
Channel: mel wiki
Viewing all articles
Browse latest Browse all 610

How can I add images to my UI, without hardcoding their paths?

$
0
0
It's fun to add images to your UI's, but the biggest problem is when you give your UI to someone else, usually the hard-coded paths to the imagery break.

Python

One nice thing about authoring modules in Python is they come with a 'special' __file__ attribute. This can let the module itself (or any module that calls to it) know its save location. If you store your images in the same directory as the module, you're good to go.
In the below example, presume there is a smiley.bmp image saved in the same directory as the module:
# iconTextButtonTest.py

import os
import maya.cmds as mc

class App(object):
    def __init__(self):
        # define save location of this module:
        self.path = os.path.dirname(os.path.abspath(__file__))

        if mc.window(self.name, exists=True):
            mc.deleteUI(self.name)

        self.window = mc.window(self.name, resizeToFitChildren=True)
        self.rootLayout = mc.columnLayout(adjustableColumn=True, columnAttach=('both', 5))
        # Create icon based on relative path:
        self.button = mc.iconTextButton( style='iconOnly', image=os.path.join(self.path, "smiley.bmp"))

        mc.showWindow()

App()

Mel

A older mel convention I've used is this: Author an "image finder" script, and save it in the same dir as your images. You can then use that script to define your image path during UI creation.
// save this as imageFinder.mel, and save it in the same directory as your images.
global proc string imageFinder()
	{
	string $description = `whatIs imageFinder`;
	string $path = `substitute "Mel procedure found in: " $description ""`;
	string $dir = dirname($path);
	return $dir;
	}
Now, inside of your UI, you can call to this script to find the location of your images, and embed that path at UI creation time:
// UI code here......
string $imagePath = `imageFinder`;
string $image = ($imagePath + "/foo.bmp");
image -image $image -h 128 -w 128;
// finish UI code....
Notes:
  • This is just and example: You will need a uniquely named "imageFinder.mel" script for each directory you'll be searching for images in. I usually name them based on the script that is calling to the images.
  • The first time you enter the 'imageFinder' script in Maya, it won't work when called to, since Maya will think the imageFinder procudrue was 'entered interactively'. You'll either need to call the source command on the imageFinder script after it's been saved, or simply restart Maya. It will work from that point on.
  • You can use this same technique to have a script's "help" menu\button point to a 'help.html' file; again, with non hard-coded paths.


Viewing all articles
Browse latest Browse all 610

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>