How to play sounds on python with tkinter - python-3.x

I have been working on a sort of 'Piano' on python. I have used tkinter as the ui,
and this is how it goes:
from tkinter import*
tk =Tk()
btn = Button(tk, text="c note", command = play)
How do I define the function play to play a sound when I press it?
Please Help.

Add these two pieces of code:
from winsound import *
&
command = lambda: Playsound("click_one.wav", SND_FILENAME)
If you don't like lambda then you can define a function before the creation of the button:
def play():
return PlaySound("click_one.wav", SND_FILENAME)
You can also define a lambda function:
play = lambda: PlaySound("click_one.wav", SND_FILENAME)

You can use pygame! It will not create a different window.
Check out Pygame's official site for more amazing functions like getting length.
There are two types of sound you can play sound or even music. Each supports pros and cons.
Tkinter doesn't support audio. You can even use pyglet or other modules.
Example code:
import pygame
from tkinter import *
root = Tk()
pygame.init()
def play():
pygame.mixer.music.load("Musics/example.mp3") #Loading File Into Mixer
pygame.mixer.music.play() #Playing It In The Whole Device
Button(root,text="Play",command=play).pack()
root.mainloop()

Related

Converting Python 2.7 to Python 3 with tkinter

I have a working application using Python 2.7 and Tkinter that uses these constructs:
from Tkinter import *
import Tkinter
import tkFileDialog
class Window(Frame):
#...
# other functional code
#...
def ChangeCWD(self): #CWD is current working directory
root = Tkinter.Tk()
root.withdraw()
directory = tkFileDialog.askdirectory( ... )
root = Tk()
root.mainloop()
It has labels, buttons, canvas, multiple frames and file dialogue boxes and it all works nicely.
I have begun updating the code to work on Python 3.5 and, so far all functions seem to work except for the file dialog. This is where I have got to so far:
from tkinter import *
import tkinter
import tkinter.filedialog
class Window(Frame):
#...
# other functional code
#...
def ChangeCWD(self): #CWD is current working directory
root = tkinter.Tk()
root.withdraw()
directory = filedialog.askdirectory( ... )
root = Tk()
root.mainloop()
However this code produces the error
"NameError: name 'filedialog' is not defined"
when the filedialog.askdirectory() statement is reached. Could anyone provide any help to understand what I should do to correct the situation please?
As an aside, please be gentle with me! I've always been rather mystified by the various ways of invoking import statements and how to use "tk." or "root." before some function calls. There are simply too many conflicting explanations out on the web that I can't get a clear picture.
You use import tkinter.filedialog, which imports tkinter.filedialog with the namespace tkinter.filedialog, then you try to use filedialog in your code.
Pick one of these two:
change your call to tkinter.filedialog.askdirectory( ... )
change your import to import filedialog from tkinter, which will import tkinter.filedialog with the namespace filedialog.
Note: from tkinter import * might seem like it should import filedialog, but that * does not import submodules unless the package has explicitly specified that they should.

Tkinter textvariable does not work in a secondary window?

Because when I use textvariable from a secondary window called from a command in another window the variable.set () is not reflected in that secondary window.
example:
import tkinter as tk
def test():
ven=tk.Tk()
v1=tk.StringVar()
v1.set('TEST')
print(v1.get())
tk.Label(ven, textvariable=v1).pack()
ven.mainloop()
win=tk.Tk()
tk.Button(text='BOTON',command=test).pack()
win.mainloop()
In this case the message 'TEST' set through 'set' is not registered in the Label textvariable..
Why does this happen?
Your problem comes from the fact that you have several Tk instances running simultaneously. Tkinter is based on the the Tk gui framework which is a tcl library. Therefore each Tk instance is not just a window, it's also a tcl interpreter, therefore, when you have several Tk instances, they cannot share StrinVar because the value of the StrinVar is defined in one interpreter (here win) which does not communicate with the other one (ven).
To avoid this kind of issue, just don't use several Tk instances, use Toplevel windows instead:
import tkinter as tk
def test():
ven = tk.Toplevel(win)
v1 = tk.StringVar(win)
v1.set('TEST')
print(v1.get())
tk.Label(ven, textvariable=v1).pack()
win = tk.Tk()
tk.Button(text='BOTON', command=test).pack()
win.mainloop()

grab image from clipbroad fuction pyhon in linux

I am looking for a method in which I can grab the image which is on the clipboard and assign it to the background of a pygame screen. I am trying to make an app in which a user can quickly annotate a captured image in linux. Below is a an example of what I am talking about. Unfortunately these modules do not work in linux. It's not the complete code and I have just included it to make my question clearer.
import pygame
from PIL import ImageTk, ImageGr
pygame.init()
def backgroundimage():
while True:
clipimage = ImageGrab.grabclipboard()
screen = pygame.display.set_mode(([800,800]), pygame.NOFRAME)
screen.fill((clipimage))
if __name__ == '__main__':
backgroundimage()

Im having trouble trying to time the update of a tkinter label image

I am trying to make a basic 4 frame animation, I cannot use a tkinter canvas as I want it to use the art which I have drawn (the files). There is nothing wrong with the file type as I have tested it on its own. However the code seems to just remove the window for the 6 seconds and then show the final frame.
import time
import tkinter
window=tkinter.Tk()
frame1=tkinter.PhotoImage(file="file1.ppm")
frame2=tkinter.PhotoImage(file="file2.ppm")
frame3=tkinter.PhotoImage(file="file3.ppm")
frame4=tkinter.PhotoImage(file="file4.ppm")
image=tkinter.Label(window,image=frame1)
image.pack()
time.sleep(2)
image.configure(image=frame2)
time.sleep(2)
image.configure(image=frame3)
time.sleep(2)
image.configure(image=frame4)
I'm not sure whether it is the "time.sleep" or the "image.configure" that is the problem but I have tried to mess around with different types of timing methods which also seem to fail.
import tkinter
window=tkinter.Tk()
frame1=tkinter.PhotoImage(file="file1.ppm")
frame2=tkinter.PhotoImage(file="file2.ppm")
frame3=tkinter.PhotoImage(file="file3.ppm")
frame4=tkinter.PhotoImage(file="file4.ppm")
image=tkinter.Label(window,image=frame1)
image.pack()
def loop(n):
frame = [frame1, frame2, frame3, frame4][n]
window.after(2000, lambda : image.configure(image=frame))
window.after(2000, lambda : loop((n+1)%4))
loop(1)

Custom sound in a message dialog box in wxPython

I was wondering is there any way to get a custom sound to play as soon as a message dialog box comes up? my only restriction is that I can only use wxPython for this, for arguments sake lets call the sound file 'music.wav' Here is my code so far (ignore the stuff about playing with text, that was me creating a dummy GUI for it to load):
import wx
import time
import winsound, sys
class ButtonTest(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,None,id,'Button/Text test frame',size=(800,500))
panel=wx.Panel(self)
button=wx.Button(panel, label='Exit', pos=(200,50), size=(-1,-1))
self.Bind(wx.EVT_BUTTON, self.closer, button)
self.Bind(wx.EVT_CLOSE, self.wincloser)
ape=wx.StaticText(panel, -1, 'This text is STATIC', (200,80))
ape.SetFont(wx.Font(25, wx.SWISS, wx.ITALIC, wx.BOLD, True,'Times New Roman'))
def beep(sound):
winsound.PlaySound('%s.wav'%sound, winsound.SND_FILENAME)
#wx.FutureCall(1000, beep('C:\Users\Chris\Desktop\music'))
box=wx.MessageDialog(None,'Is this a good test?','Query:',wx.ICON_ERROR)
answer=box.ShowModal()
box.Destroy
beep('C:\Users\Chris\Desktop\music')
def closer(self,event):
self.Close(True)
def wincloser(self,event):
self.Destroy()
if __name__=='__main__':
app=wx.PySimpleApp()
frame=ButtonTest(None,id=-1)
frame.Show()
app.MainLoop()
For Windows, there's winsound, which is built in to Python. Otherwise, you'll need an external library like pyAudio or Snack Sound. See also Play a Sound with Python

Resources