Loading Assets
Contents
Loading Assets#
Files#
PySketch provides asset hosting for your assets that you want to use in your sketches. Files can be uploaded directly to PySketch and can be accessed by their uploaded filenames. Each sketch can only access it’s own files.
from browser import document, window
python_logo = window.Image.new()
python_logo.src = 'pythonlogo.png'
document.body.appendChild(python_logo)
To protect sketches from broken media and image links, external URL’s can’t be loaded.
# Following image won't load and will show broken image icon since it's an external url.
python_logo = window.Image.new()
python_logo.src = 'https://www.python.org/static/img/python-logo.png'
document.body.appendChild(python_logo)
Scripts#
If the uploaded file extensions are js
, py
or css
, these files will be automatically included to head of the html
and this files will load as soon as code runs.
Global variables from the JavaScript file can be accessed from window module as usual.
function printGreeting(){
console.log("Hello From JavaScript Library!")
}
from browser import window
window.printGreeting()
If extension is py
it will be available as module with the filename
def print_greeting():
print("Hello From Python Module!")
import greeting
greeting.print_greeting()
External Scripts#
You may need to use some external libraries such as P5js, tensorflowjs,
threejs etc. with your sketches. You can add these external library URL’s
directly to sketches. Any URL’s added to sketch will be
added as <script>
in order, and run before the Python in the editor.
Script’s global variables can be accessed by window module.
from browser import window
# Tensorflowjs URL is added to External Script for this sketch.
# We access tf from window module and print version
print(f'Loaded TensorFlow.js - version: {window.tf.version.tfjs}')