Craven
Craven

Reputation: 3

Create a GIF for Maya with python threading

I want to add a gif element in my custom Maya UI using python. Since Maya doens't accept animated images as input I created a while loop and edit the input image. To do to that I used Timer and everything works fine, untill I rerun the script. The old thread is somehow still active (altough I kill it every time I run the script)

This is the code I have. I have a start and stop button that work exactly as they are supposed to, but if I rerun the script, the old thread is still active.

from threading import Timer
import time
import maya.cmds as cmds

global t
global N
global B

def initGif():
    global t
    global N
    global B

    terminateGif()  
    N = 0

    t = Timer(1.0, startGif)
    t.start()

def startGif():
    global N
    global t
    while N < 1000:
        if N < 1000:
            print "Hello", t # This is where the actual images would iterate instead of "Hello"
            time.sleep(5)
        else:
            terminateGif()
            continue

def terminateGif():
    global t
    global N
    N = 9999999

    try:
        t.cancel()
    except:
        t = "None"
        return

def UI():
    if cmds.window("win", exists = True):
        cmds.deleteUI("win")
    cmds.window("win", w = 500, h = 500)

    cmds.columnLayout()
    cmds.button("stop", c = lambda *args : terminateGif())
    cmds.button("start", c = lambda *args : initGif())

    cmds.showWindow("win")

UI()
initGif()

Upvotes: 0

Views: 416

Answers (1)

Green Cell
Green Cell

Reputation: 4777

The fact that you're trying to get a gif working with threading and a timer is just asking for Maya to crash, or at least slow down the scene's performance.

Instead of bearing all of the overhead, I strongly recommend you just use PySide, which is built-in to Maya anyways. Here's a simple example without having to deal with the nightmare that is threading:

from PySide2 import QtCore
from PySide2 import QtGui
from PySide2 import QtWidgets


class Win(QtWidgets.QWidget):

    def __init__(self, parent=None):
        super(Win, self).__init__(parent)

        self.setWindowTitle("Gif Example")
        self.resize(500, 500)

        self.movie = QtGui.QMovie("/PATH/TO/YOUR/GIF.gif")  # Set your gif path here.
        self.movie.setScaledSize(QtCore.QSize(150, 150))  # You can resize it too.
        self.movie.start()

        self.gif = QtWidgets.QLabel(parent=self)  # Use QLabel to display the gif.
        self.gif.setMovie(self.movie)

        self.main_layout = QtWidgets.QVBoxLayout()
        self.main_layout.addWidget(self.gif)
        self.setLayout(self.main_layout)


win = Win()
win.show()

Upvotes: 1

Related Questions