Home > Net >  How can I make a fast pixel-changing animation widget in Python 3?
How can I make a fast pixel-changing animation widget in Python 3?

Time:08-21

What I want:

I want an animation widget with fast display1 generation (meaning the delay should be smaller than 20 seconds) and with a special function to run pixel-changing animations without delay (meaning the delay should be smaller than 20 ms) in Python 3.

Wrong method:

The simplest method is a pixel panel. But it is generating very slowly2.

This is the code:

import tkinter as t

tk = t.Tk()
n = 1100
k = 900 # Display sizes
canvas = t.Canvas(tk, width =k, height = n)
canvas.grid(column = 0, row = 0)
ids = [] # Pixel identifiers
for i in range(n):
    id2 = []
    for j in range(k):
        id2.append(cv.create_rectangle(i,j,i 1,j 1,outline = "black"))
    ids.append(id2)
def animation(animation_list): # Animation function,animation_list - list of coords and colors tuples(as example,[(1, 0, "red"), (2, 1, "green")].
    global canvas
    for x, y, color in animation_list:
        canvas.itemconfig(ids[x][y],outline = color)

1 Sizes are 1100x900 pixels (990k pixels)
2 Debug (not debugger) shows 22 seconds, but it took more than a minute, and the window is lagging.

CodePudding user response:

I found it! Thanks to Mike-SMT for idea!
This is my code:

import os
import pygame as pg
from random import *

main_dir = os.path.split(os.path.abspath(__file__))[0]
data_dir = os.path.join(main_dir, "data")


def show(image):
    screen = pg.display.get_surface()
    screen.fill((255, 255, 255))
                
    screen.blit(image, (0, 0))
    pg.display.flip()


def main():
    pg.init()

    pg.display.set_mode((255, 255))
    surface = pg.Surface((255, 255))

    pg.display.flip()

    t = 0
    s = 1
    brk = 1
    while brk:
        if t >= 255:
            s = -4
        if t <= 0:
            s = 4
        t  = s
        ar = pg.PixelArray(surface)
        for y in range(255):
            for z in range(255):
                r, g, b = t%6,y,z
                ar[z,y] = (r, g, b)
        del ar
        show(surface)
        for ev in pg.event.get():
            if ev.type == pg.QUIT:
                brk = 0
                pg.display.quit()

if __name__ == "__main__":
    main()
  • Related