用python写一个随机生成人脸的窗口应用
时间: 2023-03-22 20:03:35 浏览: 197
好的,以下是用Python编写一个随机生成人脸的窗口应用程序的示例代码:
```
import tkinter as tk
import random
# 生成人脸
def generate_face():
# 设置画布大小
canvas_width = 200
canvas_height = 200
# 创建画布
canvas.delete("all")
canvas.create_rectangle(0, 0, canvas_width, canvas_height, fill="#ffffff")
# 随机生成人脸
eye_color = "#000000"
hair_color = "#000000"
skin_color = random.choice(["#ffe0bd", "#ffcd94", "#eac086", "#ffad60", "#ffe39f", "#ffc19e", "#8d5524", "#c68642", "#ffa15b"])
hair_style = random.choice(["short", "medium", "long"])
hair_length = random.randint(0, 3)
# 绘制头发
if hair_style == "short":
canvas.create_rectangle(50 - hair_length, 50 - hair_length, 150 + hair_length, 100 + hair_length, fill=hair_color, outline="")
elif hair_style == "medium":
canvas.create_oval(50 - hair_length, 50 - hair_length, 70 + hair_length, 70 + hair_length, fill=hair_color, outline="")
canvas.create_oval(130 - hair_length, 50 - hair_length, 150 + hair_length, 70 + hair_length, fill=hair_color, outline="")
canvas.create_rectangle(50 - hair_length, 70, 150 + hair_length, 100 + hair_length, fill=hair_color, outline="")
elif hair_style == "long":
canvas.create_oval(50 - hair_length, 50 - hair_length, 70 + hair_length, 70 + hair_length, fill=hair_color, outline="")
canvas.create_oval(130 - hair_length, 50 - hair_length, 150 + hair_length, 70 + hair_length, fill=hair_color, outline="")
canvas.create_oval(70 - hair_length, 60 - hair_length, 130 + hair_length, 100 + hair_length, fill=hair_color, outline="")
# 绘制脸
canvas.create_oval(50, 50, 150, 150, fill=skin_color, outline="")
# 绘制眼睛
canvas.create_oval(70, 70, 90, 90, fill=eye_color, outline="")
canvas.create_oval(110, 70, 130, 90, fill=eye_color, outline="")
# 创建窗口
window = tk.Tk()
window.title("随机生成人脸")
window.geometry("200x250")
# 创建画布
canvas = tk.Canvas(window, width=200, height=200)
canvas.pack()
# 创建按钮
button = tk.Button(window, text="生成人脸", command=generate_face)
button.pack()
# 运行窗口
window.mainloop()
```
该程序使用tkinter库创建了一个窗口,包含一个画布和一个生成人脸的按钮。当用户点击按钮时,程序将在画布上随机生成一个人脸。生成的人脸包括头发、脸、眼睛等部分,并使用随机颜色来渲染。
阅读全文