Transparent pngs with Django and matplotlib - django

I currently have a Django project, with a view function, with code like the following (code copied from this post):
from pylab import figure, axes, pie, title
from matplotlib.backends.backend_agg import FigureCanvasAgg
def test_matplotlib(request):
f = figure(1, figsize=(6,6))
ax = axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15,30,45, 10]
explode=(0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})
canvas = FigureCanvasAgg(f)
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
It creates a png from a graph and serves it directly. How can I make the background of the graph transparent in this png?

Untested, but this should work. You don't have to write to an (actual) file, a file-like object should work. This code saves the image into the response.
def test_matplotlib(request):
f = figure(1, figsize=(6,6))
ax = axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15,30,45, 10]
explode=(0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})
#canvas = FigureCanvasAgg(f)
response = HttpResponse(content_type='image/png')
f.savefig(response, transparent=True, format='png')
#canvas.print_png(response)
return response

Related

Nested frames in tkinter

Good Day,
Using tkinter, Python 3.5
I am attempting to create nested frames using for loops and lists to generate the frame names.
This works for the first level of frames within a frame, however the next level fails.
For example, this code works:
from tkinter import *
from tkinter import ttk
frameLevel1List = ['Frame1', 'Frame2', 'Frame3', 'Frame4']
frameLevel2List = ['FrameA', 'FrameB', 'FrameC', 'FrameD']
class myUI:
def __init__(self):
#create main window & frames
self.main_window = Tk()
self.main_window.title("frame2 UI V001 ")
self.main_window.configure(background='gray')
w=750
h=500
x=100
y=100
self.main_window.geometry("%dx%d+%d+%d" % (w, h, x, y))
self.userlabel = Label(self.main_window, bg='gray', fg='white', text = "user Label")
self.userlabel.pack(side="top")
self.levellabel = Label(self.main_window, bg='gray', fg='white', text = "level Label")
self.levellabel.pack(side="top")
#create bottom frame
bottomFrame = Frame(self.main_window, bg='white', height=500, width=800)
bottomFrame.pack(side=BOTTOM)
#create frames from first list
for frame in frameLevel1List:
self.frame=Frame(bottomFrame, width=800, height = 100, bg = 'green', highlightbackground="black", highlightcolor="black", highlightthickness="1")
self.frame.pack(side="top")
self.framelabel = Label(self.frame, bg='blue', fg='white', text = frame)
self.framelabel.place(x=10, y=10)
mainloop()
UI=myUI()
However, when I add a second for loop to add the second list of frames within each of the first frames, I get an error. The following code fails
from tkinter import *
from tkinter import ttk
frameLevel1List = ['Frame1', 'Frame2', 'Frame3', 'Frame4']
frameLevel2List = ['FrameA', 'FrameB', 'FrameC', 'FrameD']
class myUI:
def __init__(self):
#create main window & frames
self.main_window = Tk()
self.main_window.title("frame2 UI V001 ")
self.main_window.configure(background='gray')
w=750
h=500
x=100
y=100
self.main_window.geometry("%dx%d+%d+%d" % (w, h, x, y))
self.userlabel = Label(self.main_window, bg='gray', fg='white', text = "user Label")
self.userlabel.pack(side="top")
self.levellabel = Label(self.main_window, bg='gray', fg='white', text = "level Label")
self.levellabel.pack(side="top")
#create bottom frame
bottomFrame = Frame(self.main_window, bg='white', height=500, width=800)
bottomFrame.pack(side=BOTTOM)
#create frames from first list
for frame in frameLevel1List:
self.frame=Frame(bottomFrame, width=800, height = 100, bg = 'green', highlightbackground="black", highlightcolor="black", highlightthickness="1")
self.frame.pack(side="top")
self.framelabel = Label(self.frame, bg='blue', fg='white', text = frame)
self.framelabel.place(x=10, y=10)
#create frames from second list
for frame2 in frameLevel2List:
self.frame2=Frame(frame, width=800, height = 50, bg = 'yellow')
self.frame2.pack(side="top")
self.frame2label = Label(self.frame2, bg='blue', fg='white', text = frame2)
self.frame2label.place(x=10, y=10)
mainloop()
UI=myUI()
Here is the error message:
Traceback (most recent call last):
File "C:\Users\Nicholas Boughen\Desktop\py\rubrics\nestedFramesTest.py", line 43, in <module>
UI=myUI()
File "C:\Users\Nicholas Boughen\Desktop\py\rubrics\nestedFramesTest.py", line 36, in __init__
self.frame2=Frame(frame, width=800, height = 50, bg = 'yellow')
File "C:\Users\Nicholas Boughen\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2584, in __init__
Widget.__init__(self, master, 'frame', cnf, {}, extra)
File "C:\Users\Nicholas Boughen\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2132, in __init__
BaseWidget._setup(self, master, cnf)
File "C:\Users\Nicholas Boughen\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2110, in _setup
self.tk = master.tk
AttributeError: 'str' object has no attribute 'tk'
Anything that could help me understand what I have done wrong and create nested frames with for loops would be most appreciated.
Perhaps there's a completely different way of procedurally creating nested frames that would be better? What I'm trying to do is to generate the frame names from a list and change the interface as the list changes. So if more or fewer items are in the list, there will be more or fewer frames in the interface. The list will be edited from a different interface.
lor
After many more hours of researching other people who had similar issues, and #jasonharper comment, I have discovered that I need to save(append) the frame ID into a list as it is created, to ensure each widget remains unique.
Here is the code that does what I want it to do:
from tkinter import *
import functools
class practice:
def __init__(self,root):
self.frame_list = []
for w in range(5):
frame = Frame(root, width=800, height = 100, bg = 'green', highlightbackground="black", highlightcolor="black", highlightthickness="1")
frame.pack(side="top")
self.frame_list.append(frame)
for w in range(5):
frame = Frame(root, width=400, height = 50, bg = 'blue', highlightbackground="black", highlightcolor="black", highlightthickness="1")
frame.pack(side="top")
self.frame_list.append(frame)
for w in range(5):
frame = Frame(root, width=200, height = 25, bg = 'yellow', highlightbackground="black", highlightcolor="black", highlightthickness="1")
frame.pack(side="top")
self.frame_list.append(frame)
print('button list is', self.frame_list)
root = Tk()
root.title("frame2 UI V001 ")
root.configure(background='gray')
w=750
h=500
x=100
y=100
root.geometry("%dx%d+%d+%d" % (w, h, x, y))
Thank you, I will attempt to post questions with greater clarity in future.
lor

how to insert buttons on the west side an Image file on the East Side or simply as a background using Tk

Here is my script
# Python 2.7.14 version
from Tkinter import *
import Tkinter
import tkMessageBox
from urllib2 import urlopen
import PIL
from PIL import ImageTk
import ImageTk
FILENAME = 'Fleur_de_lys.jpg'
root = Tk()
background = Canvas(root, width=250, height=250)##AttributeError: class Tk has no attribute 'Canvas'
canvas.pack()
tk_img = ImageTk.PhotoImage( file = FILENAME)
canvas.create_image(125, 125, image=tk_img)
quit_button = tk.Button(root, text = "Quit", command = root.quit, anchor = 'w',
width = 10, activebackground = "#33B5E5")
quit_button_window = canvas.create_window(10, 10, anchor='nw', window=quit_button)
root.mainloop()
No matter what attempt I do I keep getting AttributeError: class Tk has no attribute 'Canvas' where is my error if I just create button I have no issue what so ever all work but when I attempt to have a background image everything does not work
The problem appears to be that you're creating a canvas, and storing it in a variable named background, yet the very next line you are trying to call something called 'canvas', which you've never created.
Change this:
background = Canvas(root, width=250, height=250)
canvas.pack()
...
canvas.create_image(125, 125, image=tk_img)
to this:
background = Canvas(root, width=250, height=250)
background.pack()
...
background.create_image(125, 125, image=tk_img)
I fixed the issue jpg image was not being accepted I made it with a gif. Also found how to correct the buttons location and posn.
Here is the example without all the program
canvas = Canvas(root, width = 500, height = 500, bg='black')
canvas.pack(expand=YES, fill=BOTH)
my_image = PhotoImage(file='C:\\MOTD\\fleur_de_lys.gif')
canvas.create_image(0, 0, anchor = NW, image=my_image)
b1 = Button(root, text="From the Commander", command=callback,anchor = 'w',
width = 18, activebackground = "#33B5E5")
button_window1 = canvas.create_window(10, 10, anchor='nw', window=b1)

Make part of image transparent with pyglet

I have two images, "desert" image over "winter" image:
import pyglet
desert_img = pyglet.image.load('assets/desert.jpg')
desert = pyglet.sprite.Sprite(desert_img, x=50, y=50)
winter_img = pyglet.image.load('assets/winter.jpg')
winter = pyglet.sprite.Sprite(winter_img, x=0, y=0)
window = pyglet.window.Window()
#window.event
def on_draw():
winter.draw()
desert.draw()
pyglet.app.run()
Result is:
I would like draw a square of "transparency" on desert image (winter image should be visible in this square). Is it possible ? How to do that ?
I found many question who permit to make transparency with image itself (png, alpha ... but no like i want).
Based on Torxed suggestion, replace image content with transparent bytes where we want to make it transparent:
import io
from PIL import Image
import pyglet
from PIL.PngImagePlugin import PngImageFile
def replace_content_with_transparency(img: PngImageFile, x, y, width, height):
pixels = img.load()
for i in range(x, width):
for j in range(y, height):
pixels[i, j] = (0, 0, 0, 0)
desert_png = Image.open('assets/desert.png')
replace_content_with_transparency(desert_png, 32, 32, 123, 123)
fake_file = io.BytesIO()
desert_png.save(fake_file, format='PNG')
desert_img = pyglet.image.load('img.png', file=fake_file)
desert = pyglet.sprite.Sprite(desert_img, x=50, y=50)
winter_img = pyglet.image.load('assets/winter.jpg')
winter = pyglet.sprite.Sprite(winter_img, x=0, y=0)
window = pyglet.window.Window()
#window.event
def on_draw():
winter.draw()
desert.draw()
pyglet.app.run()

Image does not display in tkinter Canvas

I am trying to create a new class of Canvas that will be able to display and resize images. However The image does not display. I searched for similar questions and all the answers said to keep a reference of the PhotoImage in the class.( This answer for example). I tried doing that in a number of ways and none worked. In this example I tried saving a reference in a dictionary. I also tried self.tkimage = ImageTk.PhotoImage(image=img) which didn't work. And also tried using globals. I assume it has something to do with the garbage collector, but don't know how to solve.
Please assist.
import Tkinter as tk
from PIL import ImageTk, Image
import numpy as np
# a subclass of Canvas
class MyCanvas(tk.Canvas):
def __init__(self,parent,**kwargs):
tk.Canvas.__init__(self,parent,**kwargs)
self.tkimg = {}
self.images = []
self.image_on_canvas = []
def my_create_image(self, *args, **kw):
img = kw['image']
self.images.append(img)
self.tkimg[img] = ImageTk.PhotoImage(image=img)
kw['image'] = self.tkimg[img]
item = self.create_image(*args, **kw)
self.image_on_canvas.append(item)
def main():
root = tk.Tk()
myframe = tk.Frame(root)
myframe.pack(fill=tk.BOTH, expand=tk.YES)
mycanvas1 = MyCanvas(myframe, width=850, height=400, bg="red", highlightthickness=0)
mycanvas2 = MyCanvas(myframe, width=850, height=400, bg="green", highlightthickness=0)
mycanvas1.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES)
mycanvas2.pack(side=tk.RIGHT, fill=tk.BOTH, expand=tk.YES)
# add some widgets to the canvas
mycanvas2.create_line(0, 100, 200, 0, fill="red", dash=(4, 4))
mycanvas2.create_rectangle(50, 25, 150, 75, fill="blue")
arr1 = np.random.random([256,256])*255
img1 = Image.fromarray(arr1)
mycanvas1.my_create_image(0, 0, image=img1, anchor=tk.NW)
root.mainloop()
if __name__ == "__main__":
main()

Obtaining matplotlib slider widget position from callback in non-global context

I wanted to use the matplotlib slider as seen in an example from a previous question (below) inside a GUI window (such as TkInter etc). But, in a non-global context, the variables for the plot ("spos, fig, ax") are not defined. My understanding is that because update is used as a callback function, one can't or shouldn't pass arguments.
If so, how can a plot be updated without global variables? or
How can I obtain the slider position outside the callback function?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
t = np.arange(0.0, 100.0, 0.1)
s = np.sin(2*np.pi*t)
l, = plt.plot(t,s)
plt.axis([0, 10, -1, 1])
axcolor = 'lightgoldenrodyellow'
axpos = plt.axes([0.2, 0.1, 0.65, 0.03], axisbg=axcolor)
spos = Slider(axpos, 'Pos', 0.1, 90.0)
def update(val):
pos = spos.val
ax.axis([pos,pos+10,-1,1])
fig.canvas.draw_idle()
spos.on_changed(update)
plt.show()
Related:
1) Another related question seems to cover this topic but does not seem to address how the position of the slider is obtained.
2) A similar question was asked and solved with Slider.set_val(). It seems in my case I would need Slider.get_val() instead.
It is possible to pass more arguments to the callback function, for example with functools.partial
def update(data, val):
pos = spos.val
ax.axis([pos,pos+10,-1,1])
fig.canvas.draw_idle()
data['position'] = pos
import functools
data = dict()
spos.on_changed(functools.partial(update, data))
plt.show()
try:
print data['position']
except KeyError:
pass
A class with __call__ method could also be used as a callback.