按Tkin中的按钮时播放音效

2024-04-26 14:12:06 发布

您现在位置:Python中文网/ 问答频道 /正文

当我按下Tkinter图形用户界面上的按钮时,如何获得音效?在

这是我的代码:

from Tkinter import *
root = Tk() #root object for the buttons
from PIL import Image, ImageTk #python imaging library

#open the images and store them in photos
image = Image.open("Jolteon.PNG")
image1 = Image.open("Eevee.PNG")
image2 = Image.open("Vaporeon.PNG")
image3 = Image.open("Flareon.PNG")
photo = ImageTk.PhotoImage(image) 
photo1 = ImageTk.PhotoImage(image1)
photo2 = ImageTk.PhotoImage(image2)
photo3 = ImageTk.PhotoImage(image3)

topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root) #some different frames
bottomFrame.pack(side=BOTTOM)

button1 = Button(topFrame, text="Eevee", fg="brown")
button2 = Button(topFrame, text="Jolteon", fg="yellow")
button3 = Button(topFrame, text="Vaporeon", fg="blue")
button4 = Button(topFrame, text="Flareon", fg="red")
button5 = Button(topFrame,image=photo)
button6 = Button(topFrame,image=photo1)
button7 = Button(topFrame,image=photo2) #sdbsdfbdfsbdfb
button8 = Button(topFrame,image=photo3)

#packages the buttons so that it can be produced
button1.pack()
button6.pack()
button2.pack() #sdbsdbsdbsdfbfdsn
button5.pack()
button3.pack()
button7.pack()
button4.pack()
button8.pack()

root.mainloop()

它显示来自Pokemon的Eevee trios的名字和图片。 我想要的是当我按下口袋妖怪的照片让它哭的时候。在

我该如何实施这一点呢?在

enter image description here


Tags: thetextimagepngtkinterbuttonrootopen
1条回答
网友
1楼 · 发布于 2024-04-26 14:12:06

您必须使用偶数处理程序(或简单方法)将鼠标单击链接到图像上:

btn = tkinter.Button(root, text='Play Sound', width=16, bg='#2ff')

btn.bind('<Button-1>', on_click)  
# binding the click of btn with the on_click function 

btn.pack()

# note the parameter 'event', since this is a even handler
def on_click(event): 
    # play music

您可以使用pygame模块,特别是可以使用它的mixer模块来播放音乐。您可以从official website轻松地为您的Python版本和Windows安装pygame模块。在

安装完成后,首先要用这个命令pygame.init()初始化Pygame modules。一旦停止使用命令pygame.quit(),请记住取消初始化这些模块。注意,您可以初始化单个模块,比如mixer模块,这正是您应该使用的模块。在

相关问题 更多 >