Maya UI Dynamic adding elements is causing a crash

So I have this code where the user can click a button in the UI, which will add more int fields to the UI. For some reason it causes Maya to crash after you add a certain amount of int fields. It varies, sometimes I can add like 20, sometimes only 1 or 2 and it crashes. Does anyone have any idea why it’s crashing randomly?

import pymel.core as pm

def create_int_field(parent):
    pm.setParent(parent)
    text = pm.text(label="IntField")
    int_field = pm.intField()
   
    def int_field_change(int_field):
        cur_value = pm.intField(int_field, query=True, value=True)
        print("My Current Value is " + str(cur_value) + " !")

    pm.intField(int_field, edit=True, changeCommand=lambda _: int_field_change(int_field))
   
def create_add_int_field_button(parent):
    pm.setParent(parent)
    button = pm.button(label="Add New Int Field")

    def add_new_int_field(parent, button):
        pm.deleteUI(button)
        create_int_field(parent)
        create_add_int_field_button(parent)

    pm.button(button, edit=True, command=lambda _: add_new_int_field(parent, button))
               

if pm.window("MyUIWindow", exists=True):
    pm.deleteUI(my_window)
   
my_window = pm.window("MyUIWindow", title="My UI Window", sizeable=True, width=350, resizeToFitChildren=True)
pm.scrollLayout()
row_column_layout = pm.rowColumnLayout(numberOfColumns=2)
#Add some initial int fields
for i in range(5):
    create_int_field(row_column_layout)
#Add a button to add more int fields
create_add_int_field_button(row_column_layout)

pm.showWindow(my_window)

The problem is the line:

pm.deleteUI(button)

You delete the UI element while you are executing the command called from this element. If I see it correctly, then you want to insert the new field before the button. Maybe you can create another layout where you place the button so you do not need to delete it.

1 Like

That’s the issue! Thank you so much, I couldn’t figure it out but it works great now :smiley:

Good to hear that it is working :slight_smile: