简体   繁体   English

在Tkinter中按下按钮时播放声音效果

[英]Play sound effect when you press a Button in Tkinter

How can I get sound effects when I press buttons on the GUI for Tkinter? 按下Tkinter的GUI上的按钮时,如何获得声音效果?

Here is my code: 这是我的代码:

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()

It displays names and pictures of the Eevee trios from Pokemon. 它显示了《口袋妖怪》中Eevee trios名字和照片。 What I want is when I press the picture of the pokemon to make the pokemon cry. 我想要的是当我按下宠物小精灵的图片使宠物小精灵哭泣时。

How would I go on about implementing this? 我将如何实施呢?

在此处输入图片说明

You have to link the click of your mouse on the image, with an even handler (or simply method): 您必须使用偶数处理程序(或简单方法)将鼠标在图像上的点击链接起来:

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

You could use the pygame module, and specifically you could use its mixer module for playing music. 您可以使用pygame模块,特别是可以使用其混音器模块播放音乐。 You could easily install the pygame module for your version of Python and for Windows from the official website . 您可以从官方网站轻松地为您的Python版本和Windows安装pygame模块。

Once the installation is finished, you have first to initialise the Pygame modules with this command pygame.init() . 安装完成后,您首先需要使用此命令pygame.init()初始化Pygame modules Remember to uninitialize the same modules once you stop using them with the command pygame.quit() . 记住,一旦停止使用pygame.quit()停止使用相同的模块,便要对其进行初始化。 Note that you can initialise single modules, like the mixer module, which is the exact one that you should use. 请注意,您可以初始化单个模块,例如mixer模块,这正是您应该使用的模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM