Skip to content

Instantly share code, notes, and snippets.

@rampantmonkey
Created August 2, 2013 14:05
Show Gist options
  • Save rampantmonkey/6140147 to your computer and use it in GitHub Desktop.
Save rampantmonkey/6140147 to your computer and use it in GitHub Desktop.
Draw a randomly colored box with `Tk` and `Thread`s.

During my code spike to explore Tk as a potential candidate for my Gameboy emulator screen I created this example. It uses threads to send events to the Tk main loop and consequently update the screen. Threads were important because I will need to trigger the screen update from other classes (specifically the cpu).

I chose to use the PPM format to store the image since it is easy to create and allows pixel manipulation. The downside is performance. The data to create the image is large (one byte per pixel). For the real thing I should be able to avoid memory allocation for every update by encapsulating the data in a class with helper methods for per pixel manipulation.

The update events must be sent from a different process. This will require forking and putting all of this code (including the require statements) inside of the child process and pulling update events from a pipe.

#!/usr/bin/env ruby
require 'tk'
require 'thread'
WIDTH=16
HEIGHT=14
class Screen
def initialize root
@root = root
color = 120
@display = TkPhotoImage.new data: (format_data color, color, color)
@label = TkLabel.new @root, image: @display
@label.pack
end
def update_pixels formatted_data
@label.configure(image: (TkPhotoImage.new data: formatted_data))
end
end
def format_data red=0, green=0, blue=0
d = "P6\n#{WIDTH} #{HEIGHT}\n255\n"
HEIGHT.times do
WIDTH.times do
d << "#{red.chr}#{green.chr}#{blue.chr}"
end
end
d
end
tkroot = TkRoot.new do
title "Pixel Manipulation"
resizable false, false
end
screen = Screen.new tkroot
Thread.abort_on_exception = true
thr = Thread.new do
loop do
screen.update_pixels format_data(rand(255), rand(255), rand(255))
end
end
tkroot.mainloop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment