python画图游戏

python制作成界面,画一个800*800的格子,分成800*800个像素,然后鼠标作为1*1像素的画笔,。点一个像素就画一个1*1px的方格

如:

 

 

 

类似B站的夏日绘板

https://live.bilibili.com/pages/1702/pixel-drawing

 

import cv2
import random
import numpy as np
img = np.ones([800,900,3])*255
idx = 0

colors = [[0,0,255], [0,255,0], [255,0,0], [255, 255, 0], [255, 0, 255], [0, 255, 255], [255, 255, 255], [0, 0, 0]]
for x in range(0, 800, 100):
	img[x:x+100, 800:900, :] = colors[idx]
	idx += 1

color = random.choice(colors)
pixelSize = 20
def on_EVENT_LBUTTONDOWN(event, x, y, flags, param):
	global color
	if event == cv2.EVENT_LBUTTONDOWN:
		if x < 800:
			x -= x % pixelSize
			y -= y % pixelSize
			cv2.rectangle(img, (x,y), (x+pixelSize-1,y+pixelSize-1), color, -1)
			cv2.imshow("image", img)
		else:
			color = img[y,x,:]

cv2.namedWindow("image")
cv2.setMouseCallback("image", on_EVENT_LBUTTONDOWN)
cv2.imshow("image", img)
cv2.waitKey(0)

被自己笑死。。

=======================================================

代码更新V1.2。

因为觉得这个很有趣,就又写了一个版本,现在支持点右键就进入连笔模式了。

import cv2
import random
import numpy as np
img = np.ones([800,900,3])*255
idx = 0

colors = [[0,0,255], [0,255,0], [255,0,0], [255, 255, 0], [255, 0, 255], [0, 255, 255], [255, 255, 255], [0, 0, 0]]
for x in range(0, 800, 100):
	img[x:x+100, 800:900, :] = colors[idx]
	idx += 1

color = random.choice(colors)
pixelSize = 20

continueStarted = False
def on_EVENT_LBUTTONDOWN(event, x, y, flags, param):
	global color
	global continueStarted
	if event == cv2.EVENT_RBUTTONDOWN:
		continueStarted = not continueStarted
	if (event == cv2.EVENT_MOUSEMOVE and continueStarted) or event == cv2.EVENT_LBUTTONDOWN:
		if x < 800:
			x -= x % pixelSize
			y -= y % pixelSize
			cv2.rectangle(img, (x,y), (x+pixelSize-1,y+pixelSize-1), color, -1)
			cv2.imshow("image", img)
		else:
			color = img[y,x,:]

cv2.namedWindow("image")
cv2.setMouseCallback("image", on_EVENT_LBUTTONDOWN)
cv2.imshow("image", img)

cv2.waitKey(0)

 

鼠标左键绘制一个像素点,鼠标右键开始连续绘图,再按一下右键停止连笔模式。

移动到最右边的有色图块,并左键,可以选择颜色。

#-*- coding:utf-8 -*-
from tkinter import *

top = Tk()
top.title("画图")

cv = Canvas(top,bg='#ffffff',bd=0,width=800, height=800)
cv.pack(side=LEFT)

ox = 0
oy = 0

def start(event):
    global ox,oy
    ox = event.x
    oy = event.y

cv.bind("<Button-1>", start)

def paint(event):
    global ox,oy
    px = event.x
    py = event.y
    cv.create_line(ox, oy, px, py, fill=color.get())
    ox = event.x
    oy = event.y

cv.bind("<B1-Motion>", paint)

color = StringVar()
color.set('#000000')

colorList = [
    ('黑色','#000000'),
    ('红色','#ff0000'),
    ('蓝色','#0000ff'),
    ('绿色','#00ff00'),
    ('黄色','#ffff00'),
    ('紫色','#ff00ff'),
]
for t,c in colorList:
    Radiobutton(top, text=t, variable=color, fg=c, value=c,indicatoron=False).pack()

Button(top, text="清除", command=lambda x=ALL: cv.delete(x)).pack()

top.mainloop()