[Python] 纯文本查看 复制代码
import audioop
import pyaudio
from tkinter import *
from PIL import Image, ImageTk
import tkinter.filedialog
import tkinter.messagebox
level = 1
def background(filename):
global im_gray
im = Image.open(filename).resize((360, 640))
im_gray = im.convert('L')
return ImageTk.PhotoImage(im)
def ask_file():
# 从本地选择一个文件,并返回文件的目录
filename: str = tkinter.filedialog.askopenfilename()
if filename != '':
try:
Image.open(filename)
except IOError:
msg = tkinter.messagebox.showinfo('提示', '请选择图片文件')
else:
msg = tkinter.messagebox.showinfo('提示', '您没有选择任何文件,将恢复原始背景')
filename = '背景图片.jpg'
return filename
def mainwindow():
global level
global im_gray, im_root
def changeimage(event):
global im_root
filename = ask_file()
im_root = background(filename)
img = ImageTk.PhotoImage(im_gray)
canvas_root.itemconfig(backid, image=im_root)
canvas_root.itemconfig(foreid, image=img)
canvas_root.image = img
root.update()
def resetlevel(event):
global level
msg = tkinter.messagebox.askokcancel('提示', '确认重置关卡?')
if msg:
level = 1
btn1.config(text='挑战\n第%d关' % level)
def record_audio():
global level
global im_gray, im_root
score = 0
basescore = int(1.5 ** (level - 1) * 1000)
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording")
for i in range(0, 1292):
data = stream.read(CHUNK)
rms = audioop.rms(data, 2)
rms -= basescore
score += rms
if score < 0:
score = 0
elif score > 1000000:
if level < 9:
msg = tkinter.messagebox.showinfo('恭喜您', '挑战成功!\n您已获得嘴强王者%d段称号!' % level)
level += 1
btn1.config(text='挑战\n第%d关' % level)
else:
msg = tkinter.messagebox.showinfo('恭喜您', '挑战成功!\n这个游戏对您来说已经没有什么意义了,\n可以去寻找更广阔的舞台。')
break
print(score)
# if i % 4 == 0:
img = im_gray.crop((0, 0, 360, 640 - int(score / 1000000 * 640)))
img = ImageTk.PhotoImage(img)
canvas_root.itemconfig(foreid, image=img)
# canvas_root.image = img
root.update()
img = im_gray.crop((0, 0, 360, 640))
img = ImageTk.PhotoImage(img)
canvas_root.itemconfig(foreid, image=img)
canvas_root.image = img
root.update()
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
# 生成窗口
root = Tk()
root.title("嗓门大挑战")
root.geometry('360x640+300+150')
root.resizable = (False, False)
im_root = background('背景图片.jpg')
img = ImageTk.PhotoImage(im_gray)
canvas_root = Canvas(root, width=360, height=640)
backid = canvas_root.create_image(0, 0, anchor=NW, image=im_root)
foreid = canvas_root.create_image(0, 0, anchor=NW, image=img)
canvas_root.bind("<Button-1>", changeimage)
canvas_root.bind("<Button-3>", resetlevel)
canvas_root.pack()
btn1 = Button(root, text='挑战\n第%d关' % level, command=record_audio)
btn1.config(font=('宋体', 20))
btn1.place(x=130, y=500, width=100, height=100)
# 显示窗口
root.mainloop()
if __name__ == '__main__':
mainwindow()