Playing mp3 files using python 2.7 buttons - TKinter - python-2.7

Hello I am trying to create a button that plays a mp3 file using TKinter so far I have the following code. I cant get it to play the mp3 file
from Tkinter import *
import os
import winsound
app = Frame(root)
app.pack(side='bottom')
button1 = Button(app, text="Enter Program", command=winsound.PlaySound('music.mp3',winsound.SND_FILENAME))
button1.pack()
Thanks

You can use pyglet library to play mp3 files but you should also have installed avbin library. (https://code.google.com/p/avbin/)
Another problem is, tkinter has its own main loop and pyglet has its own. So you should use threads. This code might give you an idea:
from Tkinter import *
from threading import Thread
import pyglet
root = Tk()
app = Frame(root)
app.pack(side='bottom')
player = pyglet.media.Player()
music_file = pyglet.media.load('foo.mp3')
def startPlaying():
player.queue(music_file)
player.play()
pyglet.app.run()
def playSound():
global sound_thread
sound_thread = Thread(target=startPlaying)
sound_thread.start()
button1 = Button(app, text="Enter Program", command=playSound)
button1.pack()
root.mainloop()
pyglet.app.exit()

You have two mistakes there:
The classic command error: When you pass an argument like this:
Button(..., command=winsound.PlaySound(...))
you're calling PlaySound and use its return value (which defaults to None), so you're passing command=None. Use lambda:
Button(..., command=lambda: winsound.PlaySound(...))
winsound is not made to play mp3s, but wavs. Use another library, suggestions can be found here.

Related

Error ALDialog Python Nao

I have a problem when using the ALDialog module on Python IDE and to load on Nao. I tried in different ways to load a dialogue but I always fall back on the same error.Runtimeerror LoadTopic::ALDialogIncorrect file myDialog.topIn the first case I write directly the text that I save in a. top file but at the time of LoadTopic () I have an error.In the second case I want to load the. top file by giving it the path. I come back to the same mistake again.Do you have a solution to my problem?Thank you very much.
import qi
import argparse
import os
import sys
from naoqi import ALProxy
def main(robot_ip, robot_port):
dialog = """
topic: ~myTopic() \n
language: enu \n
u:(test) hello \n """
file = open("myDialog.top","w")
file.write(dialog)
file.close()
# load topic
proxy = ALProxy("ALDialog",robot_ip,robot_port)
proxy.setLanguage("English")
self.topic = proxy.loadTopic("myDialog.top")
# start dialog
proxy.subscribe("myModule")
# activate dialog
proxy.activateTopic(self.topic)
if name == "main":
parser = argparse.ArgumentParser()
parser.add_argument("--ip", type=str,
default="169.254.245.164",help="Robot's IP address : '169.254.245.164'")
parser.add_argument("--port", type=int, default=9559,help="port number, the default value is OK in most cases")
args = parser.parse_args()
main(args.ip, args.port)
ALDialog.loadTopic expects an absolute filepath on the robot - it doesn't know anything about the context from which you're calling it (it could be from another computer, in which case of course it can't open that file). You need to be sure that your .top is indeed on the robot, and pass it's absolute path to ALDialog.
Once installed on the robot this path will be something like /home/nao/.local/share/PackageManager/apps/your-package-id/your-dialog-name/your-dialog-name_enu.top

PyQt4 and Qwt Error when opening

i´m trying to do a simple plot, using PyQt4 and Qwt5. When i start the app, it shows as i expected, but i can´t do anything, such as click or zoom for example. And if i minimize it, the plot disappears.
This is my code:
import sys
from PyQt4 import Qt
import numpy as np
import PyQt4.Qwt5.iqt
from PyQt4.Qwt5.qplt
class SimpleData(QwtPlot):
def __init__(self):
QwtPlot.__init__(self)
x = np.arange(-2*np.pi, 2*np.pi, 0.01)
p = IPlot(Curve(x, np.cos(x), Pen(Magenta,2), "cos(x)"),
Curve(x, np.exp(x), Pen(Red), "exp(x)", Y2),
Axis(Right, Log),"Ejemplo de PyQt con PyQwt")
x = x[0: -1: 10]
p.plot(Curve(x, np.cos(x-np.pi/4), Symbol(Circle, Yellow), "circle"),
Curve(x, np.cos(x+np.pi/4), Pen(Blue), Symbol(Square, Cyan), "Square"))
app = QApplication(sys.argv)
app.exec_()
The indentation is correct, maybe i made a mistake writting it here, but it´s ok.
Another thing, when i close the app, i get this error:
QObject::killTimers: timers cannot be stopped from another thread
[Finished in 2.6s with exit code -1073741510]
Thank you for your time and answers. I hope you can help me.

How to open a python program within python

I'm working on a program using tkinter (2.7) that when a button is clicked, it opens a separate python program. What I have been trying to do is give the button a command and define it as the separate program. This is what I have so far:
from Tkinter import *
from ttk import *
import os
app = Tk()
app.title("iClassics")
app.geometry("450x300+200+200")
#Definitions
def mTetris():
subprocess.Popen("Tetris.py")
#Heading
headlabel = Label(text="iClassics", font=("Times", 30), background=("blue")).pack()
#Buttons
buttontetris = Button(app, text="Tetris", command=mTetris).pack()
buttonpong = Button(app, text="Pong").pack()
buttonbrick = Button(app, text="Brick Breaker").pack()
buttonsnake = Button(app, text = "Snake").pack()
app.mainloop()
Why can't I open my tetris.py on click?
Take a look at popen.
You shoold call it this way:
subprocess.Popen(["python", "tetris.py"])

python 2.7 while loop, ttk.progressbar not working

I am working on a progress bar that keeps track of a certain function in pygame.
The following code causes a loop that I must force quit. And I can not figure our my error. Any help would be great.
from Tkinter import *
import ttk
import sys
import pygame
myGui = Tk()
myGui.title("Progress Bar")
myGui.geometry("400x200+200+300")
value_progress = StringVar()
pygame.mixer.init()
pygame.mixer.music.load("/home/david/Documents/aaa.mp3")
pygame.mixer.music.play()
def position():
global value_progress
while pygame.mixer.music.get_busy() == True:
value_progress.set(float(pygame.mixer.music.get_pos()))
b = Button(myGui, text="Start", )
b.pack()
p = ttk.Progressbar(myGui, variable=value_progress,
mode='determinate', length=350,
maximum= 512920)
p.pack()
I call the function from the shell. and then it stalls and does not come out of it.
This is only the progress bar portion of my work. However, it causes the program to crash every time.
Do not loop. Instead try following code:
def position():
global value_progress
if pygame.mixer.music.get_busy():
value_progress.set(float(pygame.mixer.music.get_pos()))
myGui.after(100, position)
Tk.after(ms, f) call f after specified ms millisecond.

Visual Studio Console Window Location

Is it possible to make the console window in Visual Studio show up in the same location on screen for each compile?
I always have to move it around whenever I compile because its starting location overlaps things.
By default you can change console window settings per application and windows will save them for the next time when this application is run. You may change the start location by clicking right button on the console title bar, then choosing Properties and Layout tab. Then uncheck the "Let system position window" checkbox and type the coordinates you would like.
Unfortunately Visual Studio when you run an application without the debugger (Ctrl + F5) will launch the cmd.exe /c <your app> command. So changing properties on this window will also change settings for all console sessions in the system.
This does not apply to the debug run as under the debugger VS launches just the application and so the settings apply only to its console windows.
I came here with the same problem, and was sure there must be an option in VS. I ended up writing a quick python script that runs in the background, searches for the window and sets its last position. Also optionally sets it to always on top, and persists the position in a file. Hopefully will help someone else out.
import win32api
import win32gui
import win32con
import msvcrt
import sys
import time
import threading
import pywintypes
import argparse
import re
import weakref
import pickle
def log_message(message,*args):
print(("[%s]" % message).ljust(30) ," ... ",*(str(arg) for arg in args))
def make_file_name(arguments):
return arguments.save_file_name or "window_" + re.sub("[^a-z]","_",arguments.title_text,flags=re.IGNORECASE)
def update_proc(flags,arguments):
found_pos = (0,0,500,500)
found_hwnd = -1
if arguments.save_to_file and not arguments.reset:
load_file_name = make_file_name(arguments)
try:
with open(load_file_name,"rb") as load_file:
found_pos = pickle.load(load_file)
except:pass
while not flags.exit:
try:
hwnd = win32gui.FindWindow(arguments.class_text,arguments.title_text)
if not hwnd: continue
if hwnd != found_hwnd:
log_message("new window found",hwnd)
for _ in range(10):
win32gui.SetWindowPos(hwnd,0 if not arguments.on_top else win32con.HWND_TOPMOST,*found_pos,0)
time.sleep(0.01)
log_message("setting window position",found_pos)
found_hwnd = hwnd
time.sleep(0.1)
if win32gui.IsIconic(found_hwnd):
continue
rect = win32gui.GetWindowRect(found_hwnd)
new_pos = (rect[0],rect[1],rect[2]-rect[0],rect[3]-rect[1])
#ignore negative pos
if True in [ r < 0 for r in new_pos[0:2] ]:
continue
if new_pos == found_pos:
continue
if arguments.save_to_file:
log_message("saving position",new_pos)
save_file_name = make_file_name(arguments)
try:
with open(save_file_name,"wb") as save_file:
pickle.dump(new_pos,save_file)
except:pass
else:
log_message("updading stored position",new_pos)
found_pos = new_pos
except pywintypes.error:pass
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-s","--savetofile",help="Save window settings to a file",action="store_true",dest="save_to_file")
parser.add_argument("-sfn","--savefilename",type=str,help="File name to use if --savetofile specified (or a default is generated)",dest="save_file_name")
parser.add_argument("-ot","--ontop",help="Window Always Ontop",dest="on_top",action="store_true")
parser.add_argument("-c","--class",type=str,help="Window Class Name",dest="class_text")
parser.add_argument("-r","--reset",help="Reset Window Position",action="store_true")
parser.add_argument("-t","--title",type=str,help="Window Title Text",required=True,dest="title_text")
arguments = parser.parse_args()
flags = type("", (), {"exit":False})()
update_thread = threading.Thread(target=update_proc,args=[weakref.proxy(flags),arguments])
update_thread.start()
if arguments.save_to_file:
log_message("saving to file",make_file_name(arguments))
while True:
if flags.exit: break
key = msvcrt.getch()
if key == b'q':
flags.exit = True
log_message("exiting")
break
update_thread.join()