from tkinter import * def string_to_ints(s): # convert a line of ppm pixel data to a list of ints s = s.split(" ") s2 = [] for token in s: if len(token) > 0 and token[0].isdigit(): s2.append(int(token)) return s2 def read_ppm(filename): # parse an image as a 3d array: result[r][c][rgb] is # the value of row r, column c, where rgb is 0, 1, or 2 # to select red, green, or blue inf = open(filename, "r") file_type = inf.readline() if file_type != "P3\n": return None image_size = string_to_ints(inf.readline()) image_width = image_size[0] image_height = image_size[1] pixel_range = string_to_ints(inf.readline())[0] pixels = inf.readline() ints = [] row = [] image = [] while len(pixels) > 0: ints = ints + string_to_ints(pixels) i = 0 while i < len(ints) - 2: pixel = ints[i : i + 3] row.append(pixel) if len(row) >= image_width: image.append(row) row = [] i += 3 ints = ints[i : ] pixels = inf.readline() return image def hex2(i): # hex2 is a helper function for hexcolor and draw_image # convert to hex, remove '0x' prefix, insert leading zero, trim to length 2 return ('0' + (hex(i)[2 : ]))[-2 : ] def hexcolor(color): # hexcolor converts a list [r, g, b] to a color string, "#rrggbb" return '#' + hex2(color[0]) + hex2(color[1]) + hex2(color[2]) def create_canvas(image): # create a canvas with the initial image # and return it for use in draw_image window = Tk() c = Canvas(window, width=len(image[0]), height=len(image)) c.pack() draw_image(c, image) return c # return canvas c so we can alter it later def draw_image(c, img): # draw image img on canvas c for row in range(len(img)): for col in range(len(img[0])): color = hexcolor(img[row][col]) c.create_rectangle(col, row, col + 1, row + 1, outline = color, fill = color)