自己需要找两个音频文件放到这文件的同级目录下audios下面![](https://i-blog.csdnimg.cn/blog_migrate/5bcdfd0058d1a52dd3bbebb3a5841db8.png)
# coding=utf-8
# 完整代码如下
import sys
import tkinter as tk
from tkinter import *
import random
import pygame
from PIL import ImageTk
pygame.init()
def playMusic(mp3name):
print(mp3name)
pygame.display.set_mode((1,1))
pygame.mixer.music.load(mp3name)
pygame.mixer.music.set_volume(1)
pygame.mixer.music.play()
def stopMusic():
pygame.mixer.music.stop()
#设置班级,根据班级不同的名字进行更改
class2 = ['Gjanuary', '凯文杜兰特', 'jack', '乔丹', '莫扎特', '孔子','吕布','LeBronJames','杨广']
data = class2
going = True
is_run = False
playMark = True
def lottery_roll(var1, var2):
global going
global playMark
show_member = random.choice(data)
var1.set(show_member)
if going:
#加载声音
if playMark:
playMark = False
playMusic("./audios/bg.mp3")
window.after(50, lottery_roll, var1, var2)
else:
playMark = True
stopMusic()
playMusic("./audios/result.mp3")
pygame.time.delay(300)
#进行更改效果
var2.set("恭喜 {} !!!".format(show_member))
going = True
return
def lottery_start(var1, var2):
global is_run
if is_run:
return
is_run = True
var2.set('幸运儿是你吗。。。')
lottery_roll(var1, var2)
def lottery_end():
global going, is_run
if is_run:
going = False
is_run = False
window = tk.Tk()
window.geometry('900x500+0+0')
window.title('随机答题')
window.resizable(0, 0)
bgImg = ImageTk.PhotoImage(file="images/baseImages/bg.png")
bg_label = tk.Label(window, width=900, height=900, image=bgImg)
bg_label.pack()
var1 = StringVar(value='谁是幸运儿')
show_label1 = Label(window, textvariable=var1, justify='left', anchor=CENTER, width=17, height=3, bg='#BFEFFF',
font='楷体 -40 bold', foreground='black')
show_label1.place(anchor=NW, x=250, y=20)
var2 = StringVar(value='幸运儿是你吗。。。')
show_label2 = Label(window, textvariable=var2, justify='left', anchor=CENTER, width=38, height=3, bg='#ECf5FF',
font='楷体 -18 bold', foreground='red')
show_label2.place(anchor=NW, x=250, y=240)
startImg = ImageTk.PhotoImage(file="images/baseImages/startGame.png")
gameStart = tk.Button(window,image=startImg,command=lambda:lottery_start(var1, var2), width=80, height=30,bd=0)
gameStart.place( x=330, y=175)
endImg = ImageTk.PhotoImage(file="images/baseImages/gameOver.png")
gameEnd = tk.Button(window,image=endImg,command=lambda:lottery_end(), width=80, height=30,bd=0)
gameEnd.place( x=440, y=175)
window.mainloop()