首页 > 解决方案 > Python Tkinter PIL 生成随机 200x200 图像

问题描述

在 Python Tkinter 中,这段代码

# custom indicator images
im_open = Image.new('RGBA', (15, 15), '#00000000')
im_empty = Image.new('RGBA', (15, 15), '#00000000')
draw = ImageDraw.Draw(im_open)
draw.polygon([(0, 4), (14, 4), (7, 11)], fill='yellow', outline='black')
im_close= im_open.rotate(90)

以我可以使用的格式生成三角形:

截屏


在 Python tkinter 中,此代码绘制在我无法使用的画布上:

COLORS = ['snow', 'ghost white', 'white smoke', 'gainsboro', 'floral white', 'old lace' ...]

for x in range(0, 40):

    x1 = random.randint(0,400)
    y1 = random.randint(0,400)
    x2 = random.randint(0,400)
    y2 = random.randint(0,400)
    x3 = random.randint(0,400)
    y3 = random.randint(0,400)

    my_triangle = canvas.create_polygon(x1, y1, x2, y2, x3, y3,\
                  fill = (random.sample(COLORS, 1)[0]), 
                  outline = random.sample(COLORS, 1)[0])

但是,它会创建理想的图像:

Tk 窗口输出 1


第一个代码集在内存中生成我需要的图像,但使用了我不想要的三角形。第二个代码集生成了一个我不想要但具有我想要的随机形状的画布内存映射。

为了改进第二个代码集中的随机多边形形状,可以加入圆形和矩形。第二个代码集也包含颜色名称,但随机 R:G:B 通道更可取。

要选择随机的形状和颜色,可以使用当前的YY:MM:DD或。HH:MM:SS这是在没有任何内容被编码为歌曲或在获得真实艺术品之前作为占位符时为自制音乐播放器生成随机专辑艺术品。

如果重要的话,平台是 Ubuntu 16.04.6 LTS、内核 4.14.188、Python 2.7.12 以及 Tkinter、PIL 和 Tkinter-Image(东西)。

标签: pythontkinterpython-imaging-library

解决方案


生成 PIL.Image 对象,随机生成:
形状、填充和轮廓颜色。

生成的图像被绘制到 tk.Canvas 上,用于显示;
这是无关的/用于演示目的。
(图像本身采用请求的格式。)

from datetime import datetime
from PIL import Image, ImageDraw, ImageTk
from random import randint, randrange

# Create random indicator images.

WIDTH, HEIGHT = 50, 50
COUNT = 100

# Use datetime (somehow), to generate random int.
def datetimeToInt(): 
  y, m, d, hour, min, sec = datetime.now().timetuple()[0:6]
  return y + m + d + hour + min + sec

def randRgb(): 
  return(randint(0, 255), randint(0, 255), randint(0, 255))

def randTriangle():
  x1, y1 = randrange(0, WIDTH), randrange(0, HEIGHT)
  x2, y2 = randrange(0, WIDTH), randrange(0, HEIGHT)
  x3, y3 = randrange(0, WIDTH), randrange(0, HEIGHT)
  return [(x1,y1), (x2,y2), (x3,y3)]

def randRect():
  x1, y1 = randrange(0, WIDTH), randrange(0, HEIGHT)
  x2, y2 = randrange(0, WIDTH), randrange(0, HEIGHT)
  return [(x1,y1), (x2,y2)]
  return

randEllipse = randRect

# Map: random shape creation functions -> ImageDraw methods
shapeFactories = [
  (randTriangle, ImageDraw.ImageDraw.polygon),
  (randRect, ImageDraw.ImageDraw.rectangle),
  (randEllipse, ImageDraw.ImageDraw.ellipse)
]
shapeFactoriesCount = len(shapeFactories)

imgOpenList = []
imgClosedList = []
for x in range(COUNT):
  # Get random index, within full range:
  #randIdx = randrange(0, shapeFactoriesCount)
  # Use random int, generated from datetime (somehow):
  randIdx = datetimeToInt() % shapeFactoriesCount
  shapeFactory, drawMethod = shapeFactories[randIdx]
  
  im_open = Image.new('RGBA', (WIDTH, HEIGHT), '#00000000')
  draw = ImageDraw.Draw(im_open)
  drawMethod(  # passing 'self'/'draw' explicitly to method:
    draw, shapeFactory(), fill=randRgb(), outline=randRgb()
  )
  
  imgOpenList.append(im_open)
  imgClosedList.append(im_open.rotate(90))

# The rest is just for displaying the resulting images.

import tkinter as tk

from math import floor, sqrt

root = tk.Tk()

imgOpenList = [
  ImageTk.PhotoImage(img) for img in imgOpenList
]
imgClosedList = [
  ImageTk.PhotoImage(img) for img in imgClosedList
]

imgsPerAxis = floor(sqrt(COUNT))  # rough approximation
canvas = tk.Canvas(
  root,
  width=WIDTH * imgsPerAxis * 2,  # x2: open & closed images
  height=HEIGHT * imgsPerAxis
)
canvas.pack()

for i in range(imgsPerAxis):
  for j in range(imgsPerAxis):
    canvas.create_image(
      2*j*WIDTH, i*HEIGHT, 
      image=imgOpenList[i*imgsPerAxis + j],
      anchor=tk.NW
    )
    canvas.create_image(
      (2*j+1)*WIDTH, i*HEIGHT,
      image=imgClosedList[i*imgsPerAxis + j],
      anchor=tk.NW
    )

root.mainloop()

您能否将使用这些图像的代码发布为图标*?
(* 在你的 GUI 中看起来像树视图)
(我很好奇,不记得在那里看到自定义图标。)

在此处输入图像描述


如果您想要一个合成图像而不是单个图标:

from datetime import datetime
from PIL import Image, ImageDraw, ImageTk
from random import randint, randrange

# Create random composite image.

WIDTH, HEIGHT = 200, 200
COUNT = 40

# Use datetime (somehow), to generate random int.
def datetimeToInt(): 
  y, m, d, hour, min, sec = datetime.now().timetuple()[0:6]
  return y + m + d + hour + min + sec

def randRgb(): 
  return(randint(0, 255), randint(0, 255), randint(0, 255))

def randTriangle():
  x1, y1 = randrange(0, WIDTH), randrange(0, HEIGHT)
  x2, y2 = randrange(0, WIDTH), randrange(0, HEIGHT)
  x3, y3 = randrange(0, WIDTH), randrange(0, HEIGHT)
  return [(x1,y1), (x2,y2), (x3,y3)]

def randRect():
  x1, y1 = randrange(0, WIDTH), randrange(0, HEIGHT)
  x2, y2 = randrange(0, WIDTH), randrange(0, HEIGHT)
  return [(x1,y1), (x2,y2)]
  return

randEllipse = randRect

# Map: random shape creation functions -> ImageDraw methods
shapeFactories = [
  (randTriangle, ImageDraw.ImageDraw.polygon),
  (randRect, ImageDraw.ImageDraw.rectangle),
  (randEllipse, ImageDraw.ImageDraw.ellipse)
]
shapeFactoriesCount = len(shapeFactories)

composite = Image.new('RGBA', (WIDTH, HEIGHT), '#00000000')
draw = ImageDraw.Draw(composite)
for x in range(COUNT):
  # Get random index, within full range:
  #randIdx = randrange(0, shapeFactoriesCount)
  # Use random int, generated from datetime (somehow):
  randIdx = datetimeToInt() % shapeFactoriesCount
  shapeFactory, drawMethod = shapeFactories[randIdx]
  
  drawMethod(  # passing 'self'/'draw' explicitly to method:
    draw, shapeFactory(), fill=randRgb(), outline=randRgb()
  )

# The rest is just for displaying the resulting images.
import tkinter as tk
root = tk.Tk()
compositeTk = ImageTk.PhotoImage(composite)
tk.Label(image=compositeTk).pack()
root.mainloop()

在此处输入图像描述


推荐阅读