Forum Archive

Help with Menu/window for Pythonista..

mtrevino57

I have a python program that I run on the Iphone. The script scrapes a website and create a "gauge" image that I would like to be able to display in a pop-up window. In that window I would like the option to share, save, and close the window. Since there are 11 different projects, The main ui would be a series of buttons that would each call the script with specific parameter for each project, create the gauge, and display in a window. Closing the window on the iphone should return to the main ui with the project buttons. Would be greatful for any examples out there that I could get me started in the right direction.
Thanks In Advance
Mark

mtrevino57

Here is a link to sample gauge

ccc

You can make your image above appear inline by editing your post to change dl=0 to raw=1 at the end of the url.

EDIT: ![](https://www.dropbox.com/s/dcvwbpdac20subj/IMG_1765.PNG?raw=1)

You could think of your menu view as a NavigationView and then you can use .push_view() to show one of your gauges and then .pop_view() to return to the menu.

JonB

Another option might be to create all guages in a scrollview, and use the paging_enabled parameter, to allow swipe action. You might consider having the guages be Buttons, so tapping would then pop up your Share/Save/Close menu. Or else, you would have ButtonItems for Share, Save, etc.

mtrevino57

@mtrevino57 https://www.dropbox.com/s/dcvwbpdac20subj/IMG_1765.PNG?raw=0

mtrevino57

@ccc THANKS! for your help. I will have a closer look at NavigationView and thanks as well for the tip to get the image appear inline with post.
https://www.dropbox.com/s/dcvwbpdac20subj/IMG_1765.PNG?raw=1

mtrevino57

@JonB Thanks. As it is now, I have all 11 project gauges appear one after the other in a long stream so I can scroll up, however I think your paging_enabled idea is a great one which would allow the swipe action. It works well now, but trying to expand my knowledge about Pythonista and this is very helpful.

ccc

See the EDIT above. Sorry about that.

mtrevino57

@ccc, Got it! THANKS!!!!!

ccc

So your use case is to measure water levels in various reservoirs at different altitudes?

https://en.wikipedia.org/wiki/Foss_Reservoir ?? I originally thought FOSS was Free and Open Source Software but probably not in this context.

mtrevino57

That is correct. Actually we have 11 reservoirs located in Oklahoma, Texas and Kansas. The reservoir status which is updated hourly is pulled from a website, and used to create the gauges on demand. The text background changes to match which pool the reservoir resides in at the time, blue is conservation pool, yellow is flood pool, and red is surcharge pool, all different levels behind a dam as shown

Probably way more than you wanted to know about dams ;-) Thanks for your help

Phuket2

@mtrevino57 , just a idea. Have you seen Status Board by Panic, Inc.
https://appsto.re/au/qBC0A.i
It's pretty cool. If you used Pythonista to gather the data and write out json data to somewhere on your interval, then the Status Board clients are pulling thier data rather than you pushing. Also nice to put to Apple TV.
Anyway, it's just a thought

mtrevino57

@Phuket2, Thanks I will have a look at the app! Currently the data is pulled when the python script is run and the gauges are generated at the time the script is run. Running on a set interval might be helpful in that when a reservoir goes from conservation to flood pool an alert could be generated.

Phuket2

@mtrevino57 , yes understand. Look it's still great. This is just a slightly twisted way. But in this scenario, when your script runs you would just write our a json file. The clients would just look at the latest json file, also if the gauge can not be reproduced as you would like it in the status board, you could also save a pic.
Anyway, just saying. I can just see the possibilities, at least I think I can. That status board is also very powerful , combined with Pythonista, I think it's a winner

mtrevino57

Just downloaded Status Board and think it will work well for Ipad. I am running this script on my iphone which generates the gauges and I am pretty sure I can save them to dropbox. Will be working to create a Status Board which pulls these images into a status board on the ipad and could share it from there. Interesting Thanks again!

Phuket2

@mtrevino57 , gr4at. Really, I hope it adds some value, if not , not ventured , nothing gained.
But if it works out and you are able to post some images would love to see them. I realize some time due to company constraints not so easy to post stuff

Webmaster4o

Panic is awesome. I love transmit for Mac, Coda for iOS, and Prompt for iOS. All great apps. I've heard good things about Firewatch, but I'm not much of a gamer.

I got Status Board a while back and decided it wasn't anything special. Let me know what you think, though.

mtrevino57

@Phuket2@Webmaster4o, will do. Right now I am the only one using this particular script that generates these gauges, but there are times when it would be helpful to send alerts with graphics included. Will post followups here

Phuket2

@Webmaster4o , I think status board is fantastic. Well at least in concept. Well more than that. The only thing that throws me off is the html when making your own data providers. I sort of understand why they do it, but I am not use to it. But I see the potential of that tool. But it's a use case. If you have no need for it, it's just another widget. But it has many practical applications. Well infinite applications really. Even in your room/house on the Apple TV. RSS feeds, hue light status, time zones, etc... Again, it's a use case. What do you need, want.

Webmaster4o

@Phuket2 @mtrevino57 They may also have added a lot of functionality since I use it last. I think I remember that most features were a paid upgrade when I got it last? I didn't really think it was worth the money, and it didn't seem to do anything Pythonista couldn't with matplotlib

Phuket2

@Webmaster4o , for me it's a different idea. You can write some interesting data somewhere (maybe need some html formatting code), and many clients (status board clients) can read the data. Can also send to Apple TV. So in Pythonista sill massaging data and writing it out. Granted you can do on a Mac/pc also. But I think it's a nice solution when you just want to concentrate on the data, not the ui and the distribution of data.

mtrevino57

Plan B, Looking at StatusBoard I am thinking it would be better to to merge the gauges into a single image which could then be posted to Twitter. I am thinking I would need to use Canvas but if there is a simple way, I am all ears. The final image would look something like the following

Webmaster4o

@mtrevino57 Check out PIL for this. It's really useful. The images you're using now could be easily put on a blank PIL.Image and saved.

mtrevino57

Perfect! Simple is best THANKS!!

mtrevino57

Okay using PIL, have the following in Pythonista on the Iphone, and it works great to display projects one at a time.

i=0
# set ii,jj for creating 4x3 gridded image with all projects
ii=0
jj=0
# create a grid to hold project status images
grid_image = Image.new('RGB', (942,792),'white')
thumbnailsize = 314,264
#print Image.getbbox(grid_image)
print "\f\a"
....
....code for generating charts was here
....
#---------------------------------------
## setup for gauge plot
        fig, ax = plt.subplots()
#        ax = plt.subplots()

        ax.axis('equal')
# Width of the "rings" (percentages if the largest "radius"==1)
        width = 0.2 
        kwargs = dict(colors=['#FFFFFF', '#FFFFFF', '#0077be',"#FFffFF"], startangle=0)
        kwargs_outer = dict(colors=['#FF0000', '#FFFF00', '#0000FF',"#FFffFF"], startangle=0)
#
        outside, _ = ax.pie([spspc,fpspc,cpspc,totspc], radius=1, **kwargs_outer)
        inside, _ = ax.pie([totspc-resspc,0,resspc,totspc], radius=1-width, **kwargs)
# Set the edgecolor to match background to hide "Pie Chart"
        plt.setp(outside,edgecolor='white')
        plt.setp(inside,edgecolor='white')
# set size of plot - this size works best on Iphone 5 Screen...
        fig.set_size_inches(4.75,4)
        labeltext= globals()[stcode[i]].Name +" on "+cdate+"\nStorage: "+str("%.2f" % float(storelev2[0]))+" AF\nElev: "+str(elevnow)+" ft @"+lasttime+"\nis "+str("%.2f" % cspace)+" ft below top of\n"+str(cpool[2])+": "+str(cpool[1])+" ft"
# check which pool is active to set colors for bounding box. 
        if cpool[2]=='CONSERVATION Pool':
            kwargs1 = dict(size=20,color='white',va='center',ha='center')
            ax.text(0,-.75,labeltext,bbox=dict(facecolor='blue',edgecolor='none'),fontsize=20,**kwargs1)
        elif cpool[2] == 'FLOOD Pool':
            kwargs1 = dict(size=20,color='black',va='center',ha='center')
            ax.text(0,-.75,labeltext,bbox=dict(facecolor='yellow',edgecolor='none'),fontsize=20,**kwargs1)
        elif cpool[2] == 'SURCHARGE Pool':
            kwargs1 = dict(size=20,color='white',va='center',ha='center')
            ax.text(0,-.75,labeltext,bbox=dict(facecolor='red',edgecolor='none'),fontsize=20,**kwargs1)
        else:
            ax.text(0,-.75,labeltext,fontsize=20)
#display gauge with text         
        plt.show()
#---------------------------------------
# add plt to grid

        g_img=fig

        grid_image.paste(g_img, (ii,jj))
        ii+=314
        if ii==942:
            ii=0
            jj+=264
#---------------------------------------

        i+=1
        grid_image.show()

I must be missing something, BUT if I understand this, the actual plot is stored in fig, and the size of each gauge is 314 x 264 based on saving images on iphone and looking at properties, so for a 4x3 grid the new image would be 942x792. When I run the program, I get the ValueError: cannot determine region size; use 4-item box error. I have seen plenty of examples for opening an existing image file and pasting that to a second image, but apparently I am missing something with trying to save the gauge "fig" which is displayed using plt.show(). Suggestions?

omz

@mtrevino57 Off-topic: When you paste code here, it should be surrounded by triple back-ticks or tildes (optionally followed by python) to be formatted correctly. Example:

```python
# code here...
```

I've already edited your previous post.

mtrevino57

Any chance there is a file with Posting guidelines/tips somewhere that I missed?

omz

@mtrevino57 Not really. Posts are formatted in Markdown, like on many other developer-centric sites (StackOverflow, GitHub...). There's a good cheatsheet here: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet

brumm

I think you miss a column!? 1256x792

mtrevino57

@brumm, Thanks!!!
You are Correct, as far as the size of the final image, it would be 1256. When pasting I would start a 0,314,628,942 for the x-axis and the four across should work. I am still getting the cannot determine the region size. HOWEVER!!! I am getting closer, now am able to save the plots to files, so eventually I should be able to create a gridded image and paste the files back into it. Seems a bit redundant since all I really want to do is paste the current figure/plot into a 4x3 grid. Getting the math correct on figure size, I am left with the ValueError: cannot determine region size; use 4-item box.

mtrevino57

GOT IT! The ValueError was related to how I was loading the image. And I once I got the columns and size right(Thanks brumm), it works.

Webmaster4o

@mtrevino57 You're welcome 😉

mtrevino57

YES! Thanks to EVERYONE who took a look at this, MORE EYES is better than TWO! ;-)

ccc

"Given enough eyeballs, all bugs are shallow."

ccc

@mtrevino57 Triple quoted strings combined str.format() can make your code easier to understand and faster to execute than repeated calls to str() combined with string concatenation...

fmt = '''{} on {}
Storage: {:.2f} AF
Elev: {} ft @{}
is {:.2f} ft below top of
{}: {} ft'''

print(fmt.format('Altus', '16FEB19', 109068, 1555.555, '13:00', 3.45, 'CONSERVATION Pool', 1559))

labeltext = fmt.format(globals()[stcode[i]].Name, cdate, float(storelev2[0]),
    elevnow, lasttime, cspace, cpool[2], cpool[1])
mtrevino57

@ccc! THANKS, I will give that a shot....

mtrevino57

@ccc GOT IT! THANKS Again!!!!