今天好寂寞啊,来做一个老婆生成器吧,让你的夜晚不在空虚。
话不多说,上我老婆
1.代码其实很简单,就是在一块画布上随机放上图片。首先我们创建一个WifeGenerator类,放上一块画布和一个按钮
class WifeGenerator(Tk):
def __init__(self):
super().__init__()
self.title('老婆生成器')
self.geometry('400x500')
# 画布
self.canvas = Canvas(self, width=300, height=400)
self.canvas.place(x=200, y=230, anchor='center')
# 开始按钮
self.btn_start = Button(self, text='就决定是你了', font=('宋体', 15), bd=1, command=self.begin)
self.btn_start.place(x=200, y=465, anchor='center')
2.要随机选择图片,我们可以把所有图片放在一个列表中,然后随机生成一个下标。这里教大家一个小技巧,使用推导式可以方便的把N个图片放在列表中
img_list = [str(i) + '.png' for i in range(n)]
3.图片要滚动起来,需要在一个循环中不停地随机放置图片
def timer(self):
global wife_file
# 设置随机的时间
ran_time = random.randint(2, 3) # 图片快速滚动的时间
ran_end_time = random.randint(1, 2) # 在1到2秒内滚动速度慢慢下降
while True:
self.btn_start['state'] = DISABLED
# 生成一个0~25的随机数
img_index = random.randint(0, 25)
# PIL模块是一个图像处理库,和tkinter也有很好的接口
pil_wife= Image.open('./img/wife/' + img_list[img_index])
# 重新设置图片的尺寸为300x400
pil_wife= pil_wife.resize((300, 400), Image.ANTIALIAS)
vegetable_file = ImageTk.PhotoImage(pil_vegetable)
# 把随机的图片放在画板的中间
self.canvas.create_image(150, 200, anchor='center', image=wife_file)
# 这里设置图片滚动速度的规则
if counter <= ran_time:
time.sleep(0.05)
counter += 0.05
elif counter <= (ran_time + ran_end_time/2):
time.sleep(0.1)
counter += 0.1
elif counter <= (ran_time + ran_end_time/4*3):
time.sleep(0.2)
counter += 0.2
elif counter <= (ran_time + ran_end_time):
time.sleep(0.3)
counter += 0.3
else:
self.btn_start['state'] = NORMAL
break
4.最后在按钮的command中用多线程调用这个函数timer
def begin(self):
threading.Thread(target=self.timer).start()
今天的小菊花哥哥课堂就到这里了,如有疑问和指教,欢迎交流
网友评论