Sure. One of the great things about Blender is that it's open source and its UI is written in Python. So you can just right-click on any of the Topbar menus and choose Edit Source to see how it's coded. To have this functionality you first need to enable Developer extras in the Preferences(F4->P):
Then you you get this option when you right-click stuff on the UI:
It opens a new text data block that you can find in the Text Editor.
In this case the most interesting part is how the the place in the Topbar where you want to add your menu is called, and that seems to be in the beginning of the file:
So now we can modify the "UI Menu" example from the Text Editor's Templates menu to see if it works:
import bpy
class CustomMenu(bpy.types.Menu):
bl_label = "Custom Menu"
bl_idname = "OBJECT_MT_custom_menu"
def draw(self, context):
layout = self.layout
layout.operator("wm.open_mainfile")
layout.operator("wm.save_as_mainfile").copy = True
def draw_item(self, context):
layout = self.layout
layout.menu(CustomMenu.bl_idname)
def register():
bpy.utils.register_class(CustomMenu)
bpy.types.TOPBAR_HT_upper_bar.append(draw_item)
def unregister():
bpy.utils.unregister_class(CustomMenu)
bpy.types.TOPBAR_HT_upper_bar.remove(draw_item)
if __name__ == "__main__":
register()
Unfortunately it adds the menu after all the Workspace tabs:
That's not fun at all, so we need to read more of the Topbar code, and here it is:
Apparently all the menus are in a single menu - makes sense, because you can chose not to show the menus and they are then collapsed into a single 'burger' menu. So this must be the menu. That makes things easy again as we can just add our menu to that TOPBAR_MT_editor_menus
menu.
So I change this bit:
And it works:
If you want something like a menu or an operator to be available just in some context you can use poll() classmethod:
@classmethod
def poll(cls, context):
return context.active_object is not None
You can see how it's used in the Text Editor's Templates menu examples like "Operator Simple". It works exactly the same way with menus as with operators.