How can I control where new UI elements are placed?

I have been working through several tutorials on scripting new ui elements and panels. However, there are two problems I have not been able to solve. The first is how to control where your new ui element will show up in a panel. For example, if I do the following:

class DemoPanel(bpy.types.Panel):
    bl_label = "My new Panel"
    bl_idname = "SCENE_PT_layout"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "texture"

This places a new ui element in the texture panel which is great, but how do I go about say placing it at that top of the list instead of at the bottom, or anywhere inbetween. I realize that I change the order by hand by dragging and dropping but is there a way do it through the python script. My second question is kind of related to the first and that is to find out if it is possible to place a new ui element in a specific section of a pallet. Right now when I run the above code my new ui element is present in the texture panel regardless of what I might be doing at the time. However, what I would like to do is say place a button only in the section of the panel that deals with image textures. See attached image. I realize that I can do this in But I would like to be able to do this from my script. Any ideas on how to do this would be greatly appreciated.

you can’t define the position/rank where your panels will appear, it has rather to do with order the scripts are called.

to make a panel show only if a certain condition is met, add a poll() function and check for image.type == ‘IMAGE’

Thanks. While I am still not sure how to best use the poll function. I was able to get this to work.

class GetButtonLocation():
    def poll(cls, context):
        tex = context.texture
        engine = context.scene.render.engine
        return tex and ((tex.type == cls.tex_type and not tex.use_nodes) and (engine in cls.COMPAT_ENGINES))

class CreateCustomButton(GetButtonLocation, Panel):
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "texture"
    bl_label = "My Custom Button"
    tex_type = 'IMAGE'

well, you can put the poll() directly into CreateCustomButton class

You could define your draw function , sans panel class, and just append it to the panel in question, like this:

bpy.types.TEXTURE_PT_colors.append(lambda s,c:s.layout.label("here?"))

there’s also prepend, which would add it at the top, but i’d consider both as hacks…