PyQt4 and Qwt Error when opening - python-2.7

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.

Related

Jupyter/ipython notebook : how to prevent plot redraw using interactive widget

I am struggling to have construct an interactive tool in jupyter notebook. Based on the discussion here : IPython Notebook widgets for Matplotlib interactivity, I've build the following example:
%matplotlib notebook
import matplotlib.pyplot as plt
from ipywidgets import Select,interactive,Dropdown
from IPython.display import display
fig,ax = plt.subplots()
ax.plot(range(5))
vline = ax.axvline(1, color='k')
hline = ax.axhline(0.5, color='k')
def set_cursor(x, y):
vline.set_xdata((x, x))
hline.set_ydata((y, y))
ax.figure.canvas.draw_idle()
interactive(set_cursor, x=ax.get_xlim(), y=ax.get_ylim())
It works pretty well except that that the last line (interactive...) has to be run in a different cell.
If I want to launch everything in the same cell (or from the same object if use a Class approach, which is what I want at the end), I have to use the following code:
%matplotlib notebook
import matplotlib.pyplot as plt
from ipywidgets import Select,interactive,Dropdown
from IPython.display import display
fig,ax = plt.subplots()
ax.plot(range(5))
vline = ax.axvline(1, color='k')
hline = ax.axhline(0.5, color='k')
def set_cursor(x, y):
vline.set_xdata((x, x))
hline.set_ydata((y, y))
ax.figure.canvas.draw_idle()
display(fig)
tool = interactive(set_cursor, x=ax.get_xlim(), y=ax.get_ylim())
display(tool)
But in this case, the complete figure is redraw each time a new value is selected in a widget
Is there any possibility to get everything launch smoothly from the same cell ?
Any idea is more than welcome !

Playing mp3 files using python 2.7 buttons - TKinter

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.

Rapid Gui with Qt and Python Chaper4 Alert.pyw Not Popping

i'm starting to learn Qt and i'm currently doing the alert.pyw example. The example works just fine but i wanted to test it if it really works like it's described so when i pass the time parameter i acctually put in a time to be reached (for example, now it's 11:34 and i passed 11:35 or 11:36, just to be sure i tried a few times with longer waiting times and i actually waited after time it should have popped up for a few minutes).
Well, when the set time is reachead no window actually pop up to "Wake me up".
Is this because the code actually isn't meant to work or there is something weird going on?
Here is the code:
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future_builtins import *
import sys
import time
from PyQt4.QtCore import (QTime, QTimer, Qt, SIGNAL)
from PyQt4.QtGui import (QApplication, QLabel)
app = QApplication(sys.argv)
try:
due = QTime.currentTime()
message = "Alert!"
if len(sys.argv) < 2:
raise ValueError
hours, mins = sys.argv[1].split(":")
due = QTime(int(hours), int(mins))
if not due.isValid():
raise ValueError
if len(sys.argv) > 2:
message = " ".join(sys.argv[2:])
except ValueError:
message = "Usage: alert.pyw HH:MM [optional message]" # 24hr clock
while QTime.currentTime() < due:
time.sleep(20) # 20 seconds
label = QLabel("<font color=red size=72><b>{0}</b></font>"
.format(message))
label.setWindowFlags(Qt.SplashScreen)
label.show()
QTimer.singleShot(60000, app.quit) # 1 minute
app.exec_()
Thanks for any help

Python - Matplotlib responsive window without blocking

I have a main thread which collects data in real time. When it receives some data it adds the data to a stack. The stack is then processed by another thread which writes the data to disk.
Now i also want this thread to plot some of the data (every minute or so). I really like Matplotlibs 3D scatter plot (you can rotate and zoom with the mouse etc.). Problem is, either the window is blocking, so my program doesn't continue, or, if I make it non-blocking, the window controls are unresponsive (no mouse rotation etc.). Is there a way I can have both? I tried doing the Matplotlib stuff in another thread, but then it complains it needs to be in the main thread (tried this with default QT4 and TkAgg backend).
File: plotter.py
import numpy as np
from pylab import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import threading
class plotter:
def showThread(self):
plt.show()
def __init__(self):
print "plotter initializing"
# plt.ion()
fig = plt.figure()
ax1 = Axes3D(fig)
self.ax1 = ax1
ax1.scatter([0],[0],[0])
ax1.set_xlim3d(0,512,30)
ax1.set_ylim3d(0,256,30)
ax1.set_zlim3d(0,20,5)
plt.draw()
t = threading.Thread(target=self.showThread)
t.start()
def plot(self,xlist,ylist,zlist):
#This function updates the plot..
self.ax1.scatter(xlist,ylist,zlist)
self.ax1.set_xlim3d(0,512,30)
self.ax1.set_ylim3d(0,256,30)
self.ax1.set_zlim3d(0,20,5)
plt.draw()
Error TkInter:
TclError: out of stack space (infinite loop?)
Error QT4 (gives more errors):
File "/usr/lib64/python2.6/site-packages/matplotlib/backends/backend_qt4.py", line 73, in mainloop
signal.signal(signal.SIGINT, signal.SIG_DFL)
ValueError: signal only works in main thread

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.