def main(argv): corna = int(argv[1]) cornb = int(argv[2]) side = float(argv[3]) window = Tk() canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="#000000") canvas.pack() img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH / 2, HEIGHT / 2), image=img, state="normal") x_squareds = [ x * x for x in [corna + (side * (i / 100.0)) for i in range(WIDTH)] ] y_squareds = [ y * y for y in [cornb + (side * (j / 100.0)) for j in range(HEIGHT)] ] lines = [] for yy in y_squareds: horizontal_line = '{' + ' '.join(color(xx, yy) for xx in x_squareds) + '}' lines.append(horizontal_line) img.put(' '.join(lines)) mainloop()
def read_p3(token): next_token = lambda: next(token) assert 'P3' == next_token(), 'Invalid PPM type' width, height, max_value = (int(next_token()) for i in range(3)) root = Tk() image = PhotoImage(width=width, height=height) for h in range(0, height): for w in range(0, width): if max_value is 255: mask = '#%02x%02x%02x' else: mask = '#%04x%04x%04x' color = mask % tuple(int(next_token()) for i in range(3)) image.put(color, (w, h)) canvas = Canvas(root, width=600, height=500) canvas.grid(row=0, column=0, sticky='news') vertical_scrollbar = Scrollbar(root, orient='vertical', command=canvas.yview) vertical_scrollbar.grid(row=0, column=1, sticky='nes') horizontal_scrollbar = Scrollbar(root, orient='horizontal', command=canvas.xview) horizontal_scrollbar.grid(row=1, column=0, sticky='ews') canvas.configure(yscrollcommand=vertical_scrollbar.set) canvas.configure(xscrollcommand=horizontal_scrollbar.set) canvas.create_image(0, 0, image=image, anchor=NW) root.update() root.minsize(root.winfo_width(), root.winfo_height()) root.mainloop()
def draw_row(image: PhotoImage, to: tuple, tiles: List[Tile]): (x, y) = to colors = " ".join( (" ".join([tile_colors[t]] * scale_factor) for t in tiles)) row = "{ " + colors + " }" for i in range(scale_factor): image.put(row, to=(x * scale_factor + 1, y * scale_factor + i + 1))
class Screen: def __init__(self, width, height, level, player): self.level = level self.width = width self.height = height self.player = player self.raycasting = RayCasting(width, height, level, player) self.image = None def render(self): self.tk = Tk() self.canvas = Canvas(self.tk, width=self.width, height=self.height) self.canvas.pack() self.image = PhotoImage(width=self.width, height=self.height) self.canvas.create_image(0, 0, image=self.image, anchor="nw", state="normal") self.tk.after(100, self.update) self.tk.mainloop() def update(self): self.raycasting.raycasting() pixels = self.raycasting.get_pixels() self._update_image(pixels) self.canvas.update() self.player.angle += 2 self.tk.after(100, self.update) def _update_image(self, pixels): for y in range(self.height): for x in range(self.width): data = pixels[y * self.width + x] self.image.put(data, (x, y))
def makeTransparent(img, colorToMakeTransparentInHexFormat): newPhotoImage = PhotoImage(width=img.width(), height=img.height()) for x in range(img.width()): for y in range(img.height()): rgb = '#%02x%02x%02x' % img.get(x, y) if rgb != colorToMakeTransparentInHexFormat: newPhotoImage.put(rgb, (x, y)) return newPhotoImage
def switchColors(img, currentColorInHexFormat, futureColorInHexFormat): newPhotoImage = PhotoImage(width=img.width(), height=img.height()) for x in range(img.width()): for y in range(img.height()): rgb = '#%02x%02x%02x' % img.get(x, y) if rgb == currentColorInHexFormat: newPhotoImage.put(futureColorInHexFormat, (x, y)) else: newPhotoImage.put(rgb, (x, y)) return newPhotoImage
def paint_swatch(image: PhotoImage, row: int, column: int, color: Tuple[int, int, int]): """ Paint a color swatch on the palette in (row, column). """ if column < 0 or column >= PALETTE_COLUMNS: raise ValueError('bad column') if row < 0 or row >= PALETTE_ROWS: raise ValueError('bad row') x_start = column * SWATCH_SIZE y_start = row * SWATCH_SIZE for x in range(x_start, x_start + SWATCH_SIZE - 1): for y in range(y_start, y_start + SWATCH_SIZE - 1): image.put("#%02x%02x%02x" % color, (x, y))
def plot(self): t = Tk() WIDTH, HEIGHT = 800, 800 canvas = Canvas(t, width=WIDTH, height=HEIGHT, bg="#000000") canvas.pack() img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH / 2, HEIGHT / 2), image=img, state="normal") for i in range(len(self.s_)): for j in range(len(self.s_[i])): if self.s_[i][j] == True: img.put("#ffffff", (HEIGHT * i // len(self.s_), WIDTH * j // len(self.s_[i]))) t.mainloop()
def draw_danger_levels(canvas, x, y): img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH/2, HEIGHT//2), image=img, state="normal") for j in range(0, HEIGHT): for i in range(0, WIDTH): # RGB = red, green, blue # диапазон цвета: 0..255, 0x00..0xFF distance = sqrt((i-x)**2 + (j-y)**2) / 5 # две роли оператора % # 1 - форматирование строки # 2 - остаток от деления img.put("#%02x%02x%02x" % (255/(int(distance) % 256 + 1), 0, 0), (i, j)) return img
def render(self): """ Render the pixel array using tkinter """ tk = tkinter.Tk() screen = tkinter.Canvas(tk, width=self.width, height=self.height) photo = PhotoImage(width=self.width, height=self.height) for y in range(self.height): for x in range(self.width): pixel = self.pixels[self.width * y + x] photo.put(pixel, (x, y)) screen.create_image(0, 0, image=photo, anchor="nw") screen.pack() tk.mainloop()
def display_image(data): global XYP X, Y, P = XYP root = Tk() im = PhotoImage(width=X, height=Y) im.put(data) w = Label(root, image=im, bd=0) w.pack() mainloop()
def paint(fractal, g): screenSize = fractal.getPixels() img = PhotoImage(width=fractal.getPixels(), height=fractal.getPixels()) # Display the image on the screen canvas = Canvas(window, width=fractal.getPixels(), height=fractal.getPixels(), bg=g.getColor(0)) canvas.pack() canvas.create_image((fractal.getPixels() / 2, fractal.getPixels() / 2), image=img, state="normal") for row in range(screenSize, 0, -1): for col in range(screenSize): x = fractal.getMin()['x'] + col * fractal.getPixelSize() y = fractal.getMin()['y'] + row * fractal.getPixelSize() color = g.getColor(fractal.count(complex(x,y))) img.put(color, (col, screenSize - row)) window.update() # display a row of pixels return img
def makebw(img: tk.PhotoImage) -> tk.PhotoImage: ''' Make black&white version of image Args: img: image to convert ''' for x in range(img.width()): for y in range(img.height()): bw = sum(img.get(x, y)) // 3 if bw in (0, 255): continue img.put('#{0:02x}{0:02x}{0:02x}'.format(bw), (x, y)) return img
class Jul: def __init__(self, root, x1, y1, x2, y2): t = time.time() self.img = PhotoImage(width=wid, height=hei) canv = Canvas(root, width=wid, height=hei) canv.pack() canv.create_image(0, 0, image=self.img, anchor=NW) dx = abs(x2 - x1) / wid dy = abs(y2 - y1) / hei #c = complex(-0.8, 0.156) #c = complex(-0.74543,+0.11301) #c = complex(-0.1,0.651) #c = complex(-0.70176,-0.3842) c = complex(-0.835, -0.2321) #c = complex(-0.74434, -0.10772) #c = complex(-0.62772, 0.42193) y = y1 for j in range(hei): line = '{' x = x1 for i in range(wid): x = x + dx a = complex(x, y) for k in range(maxiter): a = a * a + c if (abs(a) > blowup): break if (k == maxiter - 1): #line += '#%02x%02x%02x ' % (255,255,255) line += '#%02x%02x%02x ' % (0, 0, 0) else: line += '#%02x%02x%02x ' % color(k) line += '}' self.img.put(line, (0, j)) canv.update() y = y - dy print(time.time() - t)
class Jul: def __init__(self, root, x1, y1, x2, y2): t = time.time() self.img = PhotoImage(width=wid, height=hei) canv = Canvas(root, width = wid, height = hei) canv.pack() canv.create_image(0, 0, image = self.img, anchor=NW) dx = abs(x2-x1)/wid dy = abs(y2-y1)/hei #c = complex(-0.8, 0.156) #c = complex(-0.74543,+0.11301) #c = complex(-0.1,0.651) #c = complex(-0.70176,-0.3842) c = complex(-0.835,-0.2321) #c = complex(-0.74434, -0.10772) #c = complex(-0.62772, 0.42193) y = y1 for j in range(hei): line = '{' x = x1 for i in range(wid): x = x + dx a = complex(x, y) for k in range(maxiter): a = a*a + c if(abs(a) > blowup): break if(k == maxiter-1): #line += '#%02x%02x%02x ' % (255,255,255) line += '#%02x%02x%02x ' % (0,0,0) else: line += '#%02x%02x%02x ' % color(k) line += '}' self.img.put(line, (0, j)) canv.update() y = y - dy print(time.time() - t)
class ImageFrame: def __init__(self, image): self.img = PhotoImage(width=WIDTH, height=HEIGHT) for row in range(HEIGHT): for col in range(WIDTH): num = image[row * WIDTH + col][C] kolor = 'BLACK' if num == 1: kolor = 'WHITE' #gray if num == 2: kolor = 'RED' self.img.put(kolor, (col, row)) c = Canvas(root, width=WIDTH, height=HEIGHT) c.pack() c.create_image(0, 0, image=self.img, anchor=NW) printElapsedTime('displayed image')
def show_image(self, width, height, pixels, row, col): """ Add an image to the gui """ self.canvas = Canvas(self, width=width, height=height) self.canvas.grid(column=col, row=row) img = PhotoImage(width=width, height=height) self.canvas.create_image((width / 2, height / 2), image=img, state="normal") self.canvas.image = img for y_index, y in enumerate(pixels): for x_index, x in enumerate(y): blue, green, red = x hex_code = rgb2hex(r=red, g=green, b=blue) img.put(hex_code, (x_index, height - y_index))
def paint_swatch(image: PhotoImage, row: int, column: int, color: Tuple[int, int, int]): """ Paint a color swatch on the palette in (row, column). """ if column < 0 or column >= PALETTE_COLUMNS: raise ValueError('bad column') if row < 0 or row >= PALETTE_ROWS: raise ValueError('bad row') # Put a slight gap between values 5 and 6 for each color to make it easier # to pick of the right value from the palette. x_start = column * SWATCH_SIZE #if column >= GAP_COLUMN: # x_start += GAP y_start = row * SWATCH_SIZE for x in range(x_start, x_start + SWATCH_SIZE - 1): for y in range(y_start, y_start + SWATCH_SIZE - 1): image.put("#%02x%02x%02x" % color, (x, y))
def paint_array(array, time): window = Tk() photo = PhotoImage(width=len(array), height=len(array)) canvas = Canvas(window, width=len(array), height=len(array), bg='#ffffff') canvas.create_image((len(array) / 2, len(array) / 2), image=photo, state='normal') canvas.pack() for i in range(len(array)): for j in range(len(array[i])): color = array.find_color(i, j) photo.put(color, (i, j)) window.update() photo.write('data/Minute ' + time + '.png', 'png') print(time) window.destroy() return
class Mandel: def __init__(self, root, x1, y1, x2, y2): t = time.time() self.img = PhotoImage(width=wid, height=hei) canv = Canvas(root, width=wid, height=hei) canv.pack() canv.create_image(0, 0, image=self.img, anchor=NW) dx = abs(x2 - x1) / wid dy = abs(y2 - y1) / hei y = y1 for j in range(hei): line = '{' x = x1 for i in range(wid): x = x + dx c = complex(x, y) a = 0 for k in range(maxiter): a = a**2 + c if (abs(a) > blowup): break if (k == maxiter - 1): line += '#%02x%02x%02x ' % (255, 255, 255) else: line += '#%02x%02x%02x ' % color(k) line += '}' self.img.put(line, (0, j)) canv.update() y = y - dy print(time.time() - t)
class Mandel: def __init__(self, root, x1, y1, x2, y2): t = time.time() self.img = PhotoImage(width=wid, height=hei) canv = Canvas(root, width = wid, height = hei) canv.pack() canv.create_image(0, 0, image = self.img, anchor=NW) dx = abs(x2-x1)/wid dy = abs(y2-y1)/hei y = y1 for j in range(hei): line = '{' x = x1 for i in range(wid): x = x + dx c = complex(x, y) a = 0 for k in range(maxiter): a = a**2 + c if(abs(a) > blowup): break if(k == maxiter-1): line += '#%02x%02x%02x ' % (255,255,255) else: line += '#%02x%02x%02x ' % color(k) line += '}' self.img.put(line, (0, j)) canv.update() y = y - dy print(time.time() - t)
def paint(fractal, imagename='branches.png'): """Paint a Fractal image into the TKinter PhotoImage canvas. This code creates an image which is 512x512 pixels in size.""" SIZE = fractal.config['pixels'] SIZE = int(SIZE) GradScheme = GradientFactory.makeGradient(fractal) # Figure out how the boundaries of the PhotoImage relate to coordinates on # the imaginary plane. minx = fractal.config['centerx'] - (fractal.config['axislength'] / 2.0) maxx = fractal.config['centerx'] + (fractal.config['axislength'] / 2.0) miny = fractal.config['centery'] - (fractal.config['axislength'] / 2.0) # Display the image on the screen window = Tk() img = PhotoImage(width=SIZE, height=SIZE) canvas = Canvas(window, width=SIZE, height=SIZE, bg=GradScheme.getColor(0)) canvas.pack() canvas.create_image((SIZE / 2, SIZE / 2), image=img, state="normal") # At this scale, how much length and height on the imaginary plane does one # pixel take? pixelsize = abs(maxx - minx) / SIZE for row in range(SIZE, 0, -1): for col in range(SIZE): x = minx + col * pixelsize y = miny + row * pixelsize i = fractal.count(complex(x, y)) color = GradScheme.getColor(i) img.put(color, (col, SIZE - row)) window.update() # display a row of pixels # Output the Fractal into a .png image img.write(imagename + ".png") print("Wrote picture " + imagename + ".png") # Call tkinter.mainloop so the GUI remains open mainloop()
class Image: def __init__(self, xres, yres): self.xres = xres self.yres = yres self.img_buf = [] for y in range(yres): Row = [] for x in range(xres): Row.append("#000000") self.img_buf.append(Row) self.window = Tk() self.canvas = Canvas(self.window, width=xres, height=yres, bg="#000000") self.canvas.pack() self.tk_img = PhotoImage(width=xres, height=yres) self.canvas.create_image((xres / 2, yres / 2), image=self.tk_img, state="normal") def Write(self, filename): self.tk_img.write(filename) def Display(self): display_str = "" for y in reversed(range(self.yres)): display_str += "{" + " ".join(self.img_buf[y]) + "} " self.tk_img.put(display_str, (0, 0)) def SetPixel(self, x, y, c): color = "#%02x%02x%02x" % (int( Saturate(c[0]) * 255.0), int( Saturate(c[1]) * 255.0), int(Saturate(c[2]) * 255.0)) self.img_buf[int(y)][int(x)] = color
def display(self): window = Tk() pixel_size = abs(self.max[0] - self.min[0]) / self.fractal.pixels photo = PhotoImage(self.fractal.name, width=self.fractal.pixels, height=self.fractal.pixels) canvas = Canvas(window, width=self.fractal.pixels, height=self.fractal.pixels, bg=self.gradient.getColor(0)) canvas.pack() canvas.create_image((self.fractal.pixels / 2, self.fractal.pixels / 2), image=photo, state="normal") for row in range(self.fractal.pixels, 0, -1): for column in range(self.fractal.pixels): x = self.min[0] + (column * pixel_size) y = self.min[1] + (row * pixel_size) color = self.gradient.getColor(self.fractal.count(complex(x,y))) photo.put(color, (column, self.fractal.pixels - row)) window.update() # display a row of pixels photo.write(f"{photo}.png") print(f"Wrote image {photo}.png") mainloop()
def show(noise): W, H = 512, 512 # The window window = Tk() # widgets can = Canvas(window, width=W, height=W, bg="magenta") can.pack() img = PhotoImage(width=W, height=H) can.create_image((W / 2, H / 2), image=img, state="normal") for x in range(W): for y in range(H): img.put(value_color(get_noise_value(x / 32, y / 32)), (x + 1, y + 1)) window.mainloop()
def MapPicture(pixel_frequency, raster=(1000, 1000)): root = Tk() img = PhotoImage(width=raster[0], height=raster[1]) for i in range(1, raster[0]): x = i for j in range(1, raster[0]): y = j img.put('#000000', (x, y)) pixel_values = [] for item in pixel_frequency.values(): pixel_values.append(item) freqstats = np.percentile(pixel_values, [25, 50, 75]) for coordinate in pixel_frequency: color = GetColor(pixel_frequency[coordinate], freqstats) img.put(color, coordinate) filename = 'heat.png' img.write(filename, format='png')
def magic(): root = Tk() canvas = Canvas(root, width=CONFIG.WIDTH, height=CONFIG.HEIGHT) root.title("mandelbrot") canvas.pack() img = PhotoImage(width=CONFIG.WIDTH, height=CONFIG.HEIGHT) canvas.create_image(((CONFIG.WIDTH + 1) // 2, (CONFIG.HEIGHT + 1) // 2), image=img, state="normal") for x in range(CONFIG.WIDTH): for y in range(CONFIG.HEIGHT // 2, -1, -1): i = mandelbrot(complex(CONFIG.real, CONFIG.imag)) color = CONFIG.colors[i // 2 % (len(CONFIG.colors))] img.put(color, (x, y)) img.put(color, (x, (CONFIG.HEIGHT - 1) - y)) CONFIG.imag += CONFIG.d_over_h CONFIG.imag = CONFIG.start[1] CONFIG.real += CONFIG.d_over_w mainloop()
class ImageFrame: def __init__(self, image): self.img = PhotoImage(width=WIDTH, height=HEIGHT) for row in range(HEIGHT): for col in range(WIDTH): num = image[row * WIDTH + col] if (num == 255) or (num < 252): kolor = '#%02x%02x%02x' % (num, num, num) #gray if num == 254: kolor = '#%02x%02x%02x' % (num, 0, 0) #red if num == 253: kolor = '#%02x%02x%02x' % (0, num, 0) #green if num == 252: kolor = '#%02x%02x%02x' % (0, 0, num) #blue if not (0 <= num < 256): exit('ERROR: num = ' + num) self.img.put(kolor, (col, row)) c = Canvas(root, width=WIDTH, height=HEIGHT) c.pack() c.create_image(0, 0, image=self.img, anchor=NW) printElapsedTime('displayed image')
def rotatedPhotoImage(img, angle, colorToMakeTransparentInHexFormat=""): angleInRads = angle * pi / 180 diagonal = sqrt(img.width()**2 + img.height()**2) xmidpoint = img.width() / 2 ymidpoint = img.height() / 2 newPhotoImage = PhotoImage(width=int(diagonal), height=int(diagonal)) for x in range(img.width()): for y in range(img.height()): # convert to ordinary mathematical coordinates xnew = float(x) ynew = float(-y) # shift to origin xnew = xnew - xmidpoint ynew = ynew + ymidpoint # new rotated variables, rotated around origin (0,0) using simoultaneous assigment xnew, ynew = xnew*cos(angleInRads) - ynew*sin(angleInRads), xnew * \ sin(angleInRads) + ynew*cos(angleInRads) # shift back to quadrant iv (x,-y), but centered in bigger box xnew = xnew + diagonal / 2 ynew = ynew - diagonal / 2 # convert to -y coordinates xnew = xnew ynew = -ynew # get pixel data from the pixel being rotated in hex format rgb = '#%02x%02x%02x' % img.get(x, y) if rgb != colorToMakeTransparentInHexFormat: # put that pixel data into the new image newPhotoImage.put(rgb, (int(xnew), int(ynew))) # this helps fill in empty pixels due to rounding issues newPhotoImage.put(rgb, (int(xnew + 1), int(ynew))) return newPhotoImage
class Paint(): def __init__(self): self.WIDTH, self.HEIGHT = 1400, 900 self.LimitX, self.LimitY = 22, 22 self.verification = False self.state_left = win32api.GetKeyState(0x01) self.mouseposx, self.mouseposy = win32api.GetCursorPos() self.window = Tk() self.canvas = Canvas(self.window, width=self.WIDTH, height=self.HEIGHT, bg="#000000") self.canvas.pack() self.img = PhotoImage(width=self.WIDTH, height=self.HEIGHT) self.canvas.create_image((self.WIDTH, self.HEIGHT), image=self.img, state="normal") self.mouseposthread = Thread(target=self.MousePosChange) self.mouseposthread.start() self.window.mainloop() def MousePosChange(self): while True: self.mouseposx, self.mouseposy = win32api.GetCursorPos() a = win32api.GetKeyState(0x01) if (a != self.state_left): print('pressed') count = 0 #for a in range(0,5): # count += 1 self.img.put("#ffffff", (self.mouseposx + count, self.mouseposy + count)) #self.verification = True self.state_left = a if (a <= -127): self.img.put("#ffffff", (self.mouseposx, self.mouseposy))
def main(argv): """ Main part of program. :param argv: :return: """ window = Tk() canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg=WHITE) canvas.pack() img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH / 2, HEIGHT / 2), image=img, state="normal") with JPTimer() as t: # compute x*x values and store them in a numpy array x_squareds = npempty((WIDTH, 1), dtype=float) for i in range(WIDTH): x = CORNA + (SIDE * i / 100.0) x_squareds[i, 0] = x * x # compute y*y values and store them in a numpy array y_squareds = npempty((HEIGHT, 1), dtype=float) for j in range(HEIGHT): y = CORNA + (SIDE * j / 100.0) y_squareds[j, 0] = y * y # compute the bits and store them in a character array lines = [] for j in range(HEIGHT): horizontal_line = '{' for i in range(WIDTH): colorbit = color(x_squareds[i, 0], y_squareds[j, 0]) horizontal_line += (' ' + colorbit) horizontal_line += '}' lines.append(horizontal_line) img.put(' '.join(lines)) print('Time required for this version was {:06,.2f} ' 'seconds'.format(t.interval)) mainloop()
def main(argv): window = Tk() screen_size = window.winfo_screenwidth(), window.winfo_screenheight() width, height = screen_size corner_x, corner_y, m = map(eval, argv[1:]) # print(screen_size) canvas = Canvas(window, width=width, height=height) canvas.pack() img = PhotoImage(width=width, height=height) canvas.create_image((width / 2, height / 2), image=img, state="normal") x_squareds = [(m * (x - corner_x))**2 for x in range(width)] y_squareds = [(m * (y - corner_y))**2 for y in range(height)] lines = [] for yy in y_squareds: horizontal_line = '{' + ' '.join(color(xx, yy) for xx in x_squareds) + '}' lines.append(horizontal_line) img.put(' '.join(lines)) mainloop()
def display_mandelbrot(): width = 700 height = 700 window = Tk() canvas = Canvas(window, width=width, height=height, bg="#ffffff") canvas.pack() img = PhotoImage(width=width, height=height) canvas.create_image((width//2, height//2), image=img, state="normal") real_range = (-2.25, .75) imag_range = (-1.5, 1.5) precision = 0.003 max_iterations = 20 real_to_x_mapper = make_linear_mapper(real_range, (0, width), int_out=True) imag_to_y_mapper = make_linear_mapper(imag_range, (0, height), int_out=True) color_mapper = make_color_mapper(max_iterations) m_set = calc_mandelbrot_for_range(real_range[0], real_range[1], imag_range[0], imag_range[1], precision, max_iterations) for item in m_set: point, result = item (x, y) = point x_pixel = real_to_x_mapper(x) y_pixel = imag_to_y_mapper(y) (in_mandelbrot_set, z_cur, steps_taken) = result color = "#000000" if not in_mandelbrot_set: color = color_mapper(steps_taken) print("plotting: {}, {} -> {}".format(x_pixel, y_pixel, color)) img.put(color, (x_pixel, y_pixel)) mainloop()
#color string table in Photoimage format #RRGGBB clr=[ ' #%02x%02x%02x' % (int(255*((i/255)**.25)),0,0) for i in range(256)] clr.append(' #000000') #append the color of the centre as index 256 #calculate mandelbrot x,y coordinates for each screen pixel xm=[xa + (xb - xa) * kx /x for kx in range(x)] ym=[ya + (yb - ya) * ky /y for ky in range(y)] #build the Photoimage string by calling mandel_pixel to index in the color table return" ".join((("{"+" ".join(clr[mandel_pixel(complex(i,j))] for i in xm))+"}" for j in ym)) #window size x=640 y=480 #corners of the mandelbrot plan to display xa = -2.0; xb = 1.0 ya = -1.27; yb = 1.27 #Tkinter window window = Tk() canvas = Canvas(window, width = x, height = y, bg = "#000000");canvas.pack() img = PhotoImage(width = x, height = y) canvas.create_image((0, 0), image = img, state = "normal", anchor = NW) #do the mandelbrot t1=clock() img.put(mandelbrot(xa,xb,ya,yb,x,y)) print(clock()-t1, ' seconds') mainloop()
class Monitor(): def __init__(self, parent): # Set up the initial variables/frame stuff self.parent = parent self.parent.geometry("378x288") self.frame = Frame(parent) self.memory_listener = MemoryListener(self.mem_action) self.print_listener = PrintListener(self.print_action) self.width = 378 self.height = 288 self.img = PhotoImage(width=self.width, height=self.height) self.canvas = None self.number_of_chars = 0 self.x = 0 self.y = 0 self.initUI() def draw_text(self, x, y, char): #Height of each letter is around 10 pixels, so start there. Then their width is 7 pixels-ish, so increase by that much. So yeah. self.canvas.create_text(x + 10 + (7 * self.number_of_chars), y + 10, text=char, fill="white") self.number_of_chars += 1 def handle_close(self): self.memory_listener.unregister() self.parent.destroy() def print_action(self, data): self.draw_text(self.x, self.y, data) self.x = (self.x + 1)%126 self.y = (self.y + 1)//126 def mem_action(self, data): address = data[0] # Video mem starts at 0x8000, and since the monitor is 120x90, and (120*90) = 0x2A30, so 0x8000 + 0x2A30 = 0xAA30 if(address >= 0x8000 and address <= 0xAA30): pixel = address - 0x8000 color = data[1] # I don't think I'm getting the RGB values correctly... # rrrrrrgggggbbbbb r = (color >> 10) & 0b111111 g = (color >> 5) & 0b11111 b = color & 0b11111 print("[VIDEO]: Pixel,", hex(pixel), "set to,", hex(data[1]), "(#%02x%02x%02x)" % (r,g,b)) #Calculate the x and y. Offset the y by 3, because the border takes up 3 pixels. x = (pixel%126)*3 y = ((pixel//126)*3)+3 print("********************Y = ", y) #Update the image with a static pink #self.img.put("#FF00FF", (x,y)) #Update the image with the given RGB, upscale dat stuff. #Row 1 self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x, y)) self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x + 1, y)) self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x + 2, y)) #Row 2 self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x, y + 1)) self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x + 1, y + 1)) self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x + 2, y + 1)) #Row 3 self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x, y + 2)) self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x + 1, y + 2)) self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x + 2, y + 2)) def initUI(self): # Deal with the UI self.parent.title("Monitor") self.frame.pack(fill=BOTH, expand=1) # Now less placeholder-y self.canvas = Canvas(self.frame, width=self.width, height=self.height, bg="#000") self.canvas.pack(fill=BOTH, expand=1) # Need to create an image so we can place individual pixels self.canvas.create_image((self.width/2, self.height/2), image=self.img, state="normal") # Handle the closing event (unregister the event listener) self.parent.protocol("WM_DELETE_WINDOW", self.handle_close)
class IO: def __init__(self, thread): # set up screen, width = 512, height = 256 self.mythread = thread self.screen = Tk() self.screen.title("Jarvis Simulator") self.screen.geometry("512x256+1600+500") self.screen.wm_maxsize(width=512, height=256) self.screen.wm_minsize(width=512, height=256) self.screen.wm_resizable(width=False, height=False) self.image = PhotoImage(width = 512, height = 256) self.label = Label(self.screen, image=self.image) self.label.grid() # set up keyboard for c in self.Keycodes.keys(): exec("self.screen.bind(\"<%s>\", self.%s)" % (c, c)) self.screen.bind("<Any-KeyPress>", self.KeyPressed) self.screen.bind("<Any-KeyRelease>", self.KeyReleased) system("xset r off") self.screen.protocol("WM_DELETE_WINDOW", self.delete_callback) def delete_callback(self): system("xset r on") self.mythread.stop() self.screen.destroy() KBD = 0 Keycodes = { "Return" : 128, "BackSpace" : 129, "Left" : 130, "Up" : 131, "Right" : 132, "Down" : 133, "Home" : 134, "End" : 135, "Prior" : 136, "Next" : 137, "Insert" : 138, "Delete" : 139, "Escape" : 140 } for i in range(1,13): k = { "F" + str(i) : 140+i } Keycodes.update(k) for key in Keycodes.keys(): code = Keycodes[key] exec("""def %s(self, event): self.KBD = %s if debugKBD: print(%s)""" % (key, code, code)) def KeyPressed(self, event): if event.char: self.KBD = ord(event.char) if debugKBD: print(str(ord(event.char))) def KeyReleased(self, event): self.KBD = 0 if debugKBD: print("Key Released.\n") def drawFill(self, color): horizontal_line = "{" + " ".join([color]*self.image.width()) + "}" self.image.put(" ".join([horizontal_line] * self.image.height())) def drawPoint(self, x, y, color): #~ print("Drawing %s point at (%i, %i)" % (color, x, y)) self.image.put(color, (x, y)) def drawmem(self, location, value): (y, x) = divmod(location,32) x = x * 16 memword = binary(value, bits=16) for i in range(0, 16): if memword[15-i] == '1': self.drawPoint(x+i, y, "green") else: self.drawPoint(x+i, y, "black")
class gui_view_tk(Tkinter.Tk): """ Class to manage the display of a saved text based grid map in a GUI - useful for large grids Grid text sample is below: ..#......2#XXXXX.............X.X......X. ..#......A#XXXX.............XX.......X.. ..#.A0000A#XXXX...X.XX......XXT......XXX ......111A#XXXX....X..X...XXXXX........X .....A1...#X..X..XXXXXXX...X.XX........X """ def __init__(self,parent): """ initialise tkinter with default parameters """ Tkinter.Tk.__init__(self,parent) self.parent = parent self.appWidth = 1900 # initial values self.appHeight = 1000 self.cell_width = 4 self.cell_height = 3 self.fname = '' self.screenWidth = self.winfo_screenwidth() self.screenHeight = self.winfo_screenheight() self.configure(bg='black') self.geometry('%dx%d+%d+%d' % (self.appWidth, self.appHeight, self.screenWidth - self.appWidth - 0, self.screenHeight - self.appHeight - 0)) WIDTH = self.appWidth HEIGHT = self.appHeight self.canvas = Canvas(self, width=WIDTH, height=HEIGHT, bg="#000000") self.canvas.pack() self.img = PhotoImage(width=WIDTH, height=HEIGHT) self.canvas.create_image(( WIDTH/2, HEIGHT/2), image=self.img, state="normal") #self.TEST_sin() # testing - draws a sin wave self.appWidth = 1900 # canvas.width self.appHeight = 1000 self.canvas.pack() def TEST_sin(self): for x in range(4 * self.appWidth): y = int(self.appHeight/2 + self.appHeight/4 * math.sin(x/80.0)) self.img.put("#ffffff", (x//4,y)) self.canvas.pack() def add_file(self, fname): self.fname = fname def show_grid_from_file(self, fname): """ reads a saved grid file and paints it on the canvas """ with open(fname, "r") as f: for y, row in enumerate(f): for x, val in enumerate(row): self.draw_cell(y, x, val) def draw_cell(self, row, col, val): """ draw a cell as position row, col containing val """ if val == 'T': self.paint_target(row,col) elif val == '#': self.paint_block(row,col) elif val == 'X': self.paint_hill(row,col) elif val == '.': self.paint_land(row,col) elif val in ['A']: self.paint_agent_location(row,col) elif val in ['1','2','3','4','5','6','7','8','9']: self.paint_agent_trail(row,col, val) def put_standard_block(self, y, x, val): """ prints a block, packing out around the y/x location with pixels up to cell width and cell height """ for j in range(0,self.cell_height): for i in range(0,self.cell_width): self.img.put(val, (x*self.cell_width+i, y*self.cell_height+j)) def paint_land(self, y, x): self.put_standard_block(y,x,'bisque') def paint_block(self, y, x): self.put_standard_block(y,x,'gray9') def paint_hill(self, y, x): self.put_standard_block(y,x,'green4') def paint_target(self, y, x): self.put_standard_block(y,x,'yellow') self.img.put('black', (x*self.cell_width+1, y*self.cell_height+1)) self.img.put('black', (x*self.cell_width+0, y*self.cell_height+1)) self.img.put('black', (x*self.cell_width+1, y*self.cell_height+0)) self.img.put('black', (x*self.cell_width+0, y*self.cell_height+0)) def paint_agent_trail(self, y, x, val): """ paint an agent trail as ONE pixel to allow for multiple agent trails to be seen in the same cell """ for j in range(1,self.cell_height-1): for i in range(1,self.cell_width-1): self.img.put(self.agent_color(val), (x*self.cell_width+i, y*self.cell_height+j)) #self.paint_agent_location(y,x,self.agent_color(val)) # old version - try to paint a single pixel trail but it looks too small #self.paint_land(y,x) # needed otherwise shows up black under dots - todo - fix this #self.img.put(self.agent_color(val), (x*self.cell_width, y*self.cell_height)) # +int(val) def paint_agent_location(self, y, x): self.put_standard_block(y,x,'red') def agent_color(self, val): """ gets a colour for agent 0 - 9 """ if val == '0': colour = 'blue' elif val == '1': colour = 'navy' elif val == '2': colour = 'firebrick' elif val == '3': colour = 'blue' elif val == '4': colour = 'blue2' elif val == '5': colour = 'blue4' elif val == '6': colour = 'gray22' elif val == '7': colour = 'gray57' elif val == '8': colour = 'red4' elif val == '9': colour = 'red3' return colour
from tkinter import Tk, Canvas, PhotoImage, mainloop WIDTH, HEIGHT, ITERATIONS = 400, 400, 400 window = Tk() canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="#000000") canvas.pack() img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal") def mandlebrot(c): z = complex(0,0) for i in range(ITERATIONS): z = z*z + c if (z.real*z.real + z.imag*z.imag) >= 4: return i return ITERATIONS for x in range(WIDTH): for y in range(HEIGHT): color = mandlebrot(complex((4*x/WIDTH) - 2.5,(4*y/HEIGHT) - 2)) color = color if color <= 255 else 255 img.put('#%02x%02x%02x' % (color%255,(40*(color//255))%4,10*((40*(color//255))//4)),(x,y)) mainloop()
def draw_gradient(canvas): img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH/2, HEIGHT//2), image=img, state="normal") # range(10) => (0, 1, 2, ..., 9) # range(5, 10) => (5, 6, 7, 8, 9) # range(5, 15, 2) => (5, 7, 9, 11, 13) for j in range(0, HEIGHT): for i in range(0, WIDTH): # RGB = red, green, blue # диапазон цвета: 0..255, 0x00..0xFF img.put("#%02x%02x%02x" % (i % 128, j % 128, 0), (i, j)) return img
class ImageFrame: def __init__(self, image, COLORFLAG = False): self.img = PhotoImage(width = WIDTH, height = HEIGHT) for row in range(HEIGHT): for col in range(WIDTH): num = image[row*WIDTH + col] if COLORFLAG == True: kolor = '#%02x%02x%02x' % (num[0], num[1], num[2]) else: kolor = '#%02x%02x%02x' % (num, num, num) self.img.put(kolor, (col, row)) c = Canvas(root, width = WIDTH, height = HEIGHT); c.pack() c.create_image(0, 0, image = self.img, anchor = NW) printElapsedTime('displayed image')