PySDL3 Desktop: SDL3_image Setup PySDL3 для Desktop: Настройка SDL3_image

A guide to loading images in your PySDL3 applications. Руководство по загрузке изображений в ваших приложениях PySDL3.

Prerequisite: Ensure you have PySDL3 installed (e.g., pip install PySDL3==0.9.11b1). Предварительное условие: Убедитесь, что PySDL3 установлен (например, pip install PySDL3==0.9.11b1).

1. Assets 1. Ресурсы

Before creating the files, download the required asset: Перед созданием файлов скачайте необходимый ресурс:

  • Download the PNG file with transparent background: right-arrow.zip Скачайте PNG-файл с прозрачным фоном: right-arrow.zip
  • Note: This is a free file taken from this link. Примечание. Это бесплатный файл, который был взят по ссылке.

2. Project Structure 2. Структура проекта

Create a project folder named pysdl3-image-app. You can keep your assets in an assets/images directory.

Создайте папку проекта с именем pysdl3-image-app. Вы можете хранить свои ресурсы в директории assets/images.

pysdl3-image-app/
├── assets/images/
│   └── right-arrow.png
└── main.py

3. Source Code 3. Исходный код

Copy this code into main.py:

Скопируйте этот код в файл main.py:

import ctypes
import os

# REQUIRED: Set environment variables BEFORE importing sdl3
os.environ["SDL_MAIN_USE_CALLBACKS"] = "1"
os.environ["SDL_RENDER_DRIVER"] = "opengl"

import sdl3

# Initialize global pointers
renderer = ctypes.POINTER(sdl3.SDL_Renderer)()
window = ctypes.POINTER(sdl3.SDL_Window)()
texture = ctypes.POINTER(sdl3.SDL_Texture)()

@sdl3.SDL_AppInit_func
def SDL_AppInit(appstate, argc, argv):
    global texture, window, renderer
    
    if not sdl3.SDL_Init(sdl3.SDL_INIT_VIDEO):
        return sdl3.SDL_APP_FAILURE

    if not sdl3.SDL_CreateWindowAndRenderer("PySDL3 Image".encode(), 250, 250, 0, window, renderer):
        return sdl3.SDL_APP_FAILURE

    # Assuming crate.png works as in your "good" example
    texturePath = "assets/images/right-arrow.png".encode()
    
    # We call the loader; it will initialize the image subsystem internally if needed
    texture = sdl3.IMG_LoadTexture(renderer, texturePath)
    
    if not texture:
        sdl3.SDL_Log("Failed to load texture: %s".encode() % sdl3.SDL_GetError())
        return sdl3.SDL_APP_FAILURE

    return sdl3.SDL_APP_CONTINUE

@sdl3.SDL_AppEvent_func
def SDL_AppEvent(appstate, event):
    if sdl3.SDL_DEREFERENCE(event).type == sdl3.SDL_EVENT_QUIT:
        return sdl3.SDL_APP_SUCCESS
    return sdl3.SDL_APP_CONTINUE

@sdl3.SDL_AppIterate_func
def SDL_AppIterate(appstate):
    sdl3.SDL_SetRenderDrawColor(renderer, 100, 100, 100, 255)
    sdl3.SDL_RenderClear(renderer)

    srcRect = sdl3.SDL_FRect(0.0, 0.0, 512.0, 512.0)
    destRect = sdl3.SDL_FRect(50.0, 50.0, 100.0, 100.0)
    
    # Pass by reference to ensure the C-side receives the correct memory address
    sdl3.SDL_RenderTexture(renderer, texture, ctypes.byref(srcRect), ctypes.byref(destRect))

    sdl3.SDL_RenderPresent(renderer)
    return sdl3.SDL_APP_CONTINUE

@sdl3.SDL_AppQuit_func
def SDL_AppQuit(appstate, result):
    global texture
    if texture:
        sdl3.SDL_DestroyTexture(texture)

4. Running the Application 4. Запуск приложения

Run the script via your terminal:

Запустите скрипт через терминал:

python main.py

Support My Work Поддержать проект

If these tutorials helped you, consider buying me a coffee! Если эти туториалы вам помогли, вы можете поддержать автора.

Sberbank (Russia only) Сбербанк (только для РФ)

Sberbank SBP QR Code

Direct transfer via phone number (Russia only) Перевод по номеру телефона (только для РФ)

+7 (917) 212-29-59

USDT TRC20

USDT TRC20 QR Code

Support via Cryptocurrency Поддержка криптовалютой

TMtY1YifNf6FKvgeFmqKGQR4NStKr3csGp