如何在Python调用DM脚本时将ImageDocument设为非脏状态(无需保存)
I get it—dealing with 100+ images and getting hit with save prompts every time you close DigitalMicrograph is such a hassle. The core issue here is that even though you’ve linked the ImageDocument to its saved file path, you haven’t explicitly reset DM’s internal "dirty" state flag. Let’s fix this.
The Missing Piece: ImageDocumentSetDirty()
DigitalMicrograph’s API has exactly what you need: the ImageDocumentSetDirty() method. Passing 0 to this method marks the document as clean (non-dirty), which tells DM it doesn’t need to prompt for saving when you close the app.
Modified Python Code
Here’s your updated code with the fix integrated. I’ve highlighted the key addition that resolves the save prompt issue:
try: import DigitalMicrograph as DM import numpy as np import execdmscript import os name = "Test image" file_path = os.path.join(os.getcwd(), "test-image.dm4") # Create image image_data = np.random.random((64, 64)) image = DM.CreateImage(image_data) image.SetName(name) # Create, save and show image document image_doc = image.GetOrCreateImageDocument() image_doc.SetName(name) image_doc.SaveToFile("Gatan Format", file_path) print("Saving image to", file_path) image_doc.ShowAtRect(100, 100, 164, 164) # Link the image to the file AND mark as non-dirty dmscript = "\n".join(( "for(number i = CountImageDocuments() - 1; i >= 0; i--){", "ImageDocument img_doc = GetImageDocument(i);", "if(img_doc.ImageDocumentGetName() == name){", "img_doc.ImageDocumentSetCurrentFile(path);", "// Explicitly mark the document as non-dirty (matches saved state)", "img_doc.ImageDocumentSetDirty(0);", "break;", "}", "}" )) svars = { "name": image_doc.GetName(), "path": file_path } with execdmscript.exec_dmscript(dmscript, setvars=svars): pass except Exception as e: print("{}: ".format(e.__class__.__name__), e) import traceback traceback.print_exc()
Why This Works
ImageDocumentSetCurrentFile(path)only associates the document with its saved location—it doesn’t automatically update the dirty state.ImageDocumentSetDirty(0)directly tells DM that the document’s current state matches what’s stored on disk, so no save prompts will pop up when you close DigitalMicrograph.
This should eliminate those repetitive save prompts for all your generated images.
内容的提问来源于stack exchange,提问作者miile7

