Python Tools - Session 10B
File Importer Tool
March 12, 2020
Session Navigation
Overview
This session creates a simple file import utility with a custom UI window. Users can browse for files using Maya's file dialog and import them directly into the scene. The tool demonstrates basic UI layout with buttons and text fields, and file system operations.
Key Concepts
- File dialog browsing with fileDialog2 - using
fileMode=1to select a single file - Text field data handling - using
setText()andgetText()to manage text field content - File import operations - using
pm.importFile()to bring external files into the scene - UI layout with rowLayout and columnLayout - arranging widgets horizontally and vertically
- None checking for cancelled dialogs - handling the case when users cancel the file browser
Code
The file importer tool (importer.py):
import pymel.core as pm
class ImporterUI():
def __init__(self):
self.window_handle = 'ImporterTool'
if pm.window(self.window_handle, exists=True):
pm.deleteUI(self.window_handle)
if pm.windowPref(self.window_handle, exists=True):
pm.windowPref(self.window_handle, remove=True)
with pm.window(self.window_handle, title='Importer', width=700, height=50):
with pm.columnLayout(rowSpacing=10):
with pm.rowLayout(numberOfColumns=2):
pm.button(label='Browse', width=100, height=30, command=pm.Callback(self.browse))
self.ui_filepath = pm.textField(width=600, height=30)
pm.button(label='Import', width=700, height=20, command=pm.Callback(self.import_file))
pm.showWindow(self.window_handle)
def browse(self):
result = pm.fileDialog2(dialogStyle=2, fileMode=1, caption='Import')
print result
if result == None:
return
self.ui_filepath.setText(result[0])
def import_file(self):
file_path = self.ui_filepath.getText()
pm.importFile(file_path)