Skip to content

Instantly share code, notes, and snippets.

@PM2Ring
Created May 15, 2017 12:06
Show Gist options
  • Save PM2Ring/754194aa37c0c1f6ad3844518973e12c to your computer and use it in GitHub Desktop.
Save PM2Ring/754194aa37c0c1f6ad3844518973e12c to your computer and use it in GitHub Desktop.
Illustrate PhotoImage pixel-plotting slowdown
#!/usr/bin/env python3
''' Use a PhotoImage to plot single pixels in a Tkinter Label
Written by PM 2Ring 2017.05.13
'''
import tkinter as tk
from time import perf_counter
import sys
class PGrid(object):
def __init__(self, width, height):
self.root = tk.Tk()
self.width, self.height = width, height
self.photo = tk.PhotoImage(width=width, height=height)
self.label = tk.Label(self.root, bg='#000', image=self.photo)
self.label.pack()
self.bodies = []
self.count = 0
self.tick = 0
self.oldtime = perf_counter()
def add_body(self, body):
self.bodies.append(body)
def update(self):
for body in self.bodies:
self.photo.put(body.color, (body.x, body.y))
body.update()
self.show_speed(200)
self.root.after(5, self.update)
def start(self):
self.update()
self.root.mainloop()
print()
def show_speed(self, maxcount=100):
self.count += 1
if self.count == maxcount:
newtime = perf_counter()
rate = maxcount / (newtime - self.oldtime)
self.oldtime = newtime
self.count = 0
#print('{:.2f}->{:.2f}'.format(rate, 1000 / rate), end='\t')
print('{:.2f}'.format(rate), end='\t')
sys.stdout.flush()
# Test the effect of blanking the PhotoImage: it speeds back up
# each time it gets blanked
self.tick += 1
if self.tick % 10 == 0:
self.photo.blank()
print()
class Body(object):
def __init__(self, pgrid, x, y, dx, dy, color):
self.pgrid = pgrid
self.x, self.y = x, y
self.dx, self.dy = dx, dy
self.color = color
pgrid.add_body(self)
def update(self):
self.x += self.dx
self.y += self.dy
if not 0 <= self.x < self.pgrid.width:
self.dx = -self.dx
self.x += self.dx
if not 0 <= self.y < self.pgrid.height:
self.dy = -self.dy
self.y += self.dy
width, height = 407, 301
pgrid = PGrid(width, height)
Body(pgrid, 140, 5, 1, 1, '#ddffaa'),
Body(pgrid, 160, 5, 1, 1, '#ffaadd'),
Body(pgrid, 180, 5, 1, 1, '#aaddff'),
pgrid.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment