How do I create a Status Icon / System Tray Icon with custom text and transparent background using Python and GTK?

Here is the code that I have so far to define the icon:

icon_bg = gtk.gdk.pixbuf_new_from_file('gmail.png')
w, h = icon_bg.get_width(), icon_bg.get_height()
cmap = gtk.gdk.Colormap(gtk.gdk.visual_get_system(), False)

drawable = gtk.gdk.Pixmap(None, w, h, 24)
drawable.set_colormap = cmap
gc = drawable.new_gc()
drawable.draw_pixbuf(gc, icon_bg, 0, 0, 0, 0, w, h)

drawn_icon = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, w, h)
drawn_icon.get_from_drawable(drawable, cmap, 0, 0, 0, 0, w, h)
icon = gtk.status_icon_new_from_pixbuf(drawn_icon)

This works to get the png into the icon, but falls short in two areas. First, transparency is not working. If I use a 22x22 png with transparent background and the image centered, I end up with sections of other active icons showing up inside of mine, like this:

http://i237.photobucket.com/albums/ff311/Raugturi/22x22_image_with_transparency.png

The icon it choose to steal from is somewhat random. Sometimes it's part of the dropbox icon, others the NetworkManager Applet.

If I instead use this code:

icon_bg = gtk.gdk.pixbuf_new_from_file('gmail.png')
w, h = icon_bg.get_width(), icon_bg.get_height()
cmap = gtk.gdk.Colormap(gtk.gdk.visual_get_system(), False)

drawable = gtk.gdk.Pixmap(None, w, h, 24)
drawable.set_colormap = cmap
gc = drawable.new_gc()
drawable.draw_pixbuf(gc, icon_bg, 0, 0, 0, 0, w, h)

drawn_icon = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 22, 22)
drawn_icon.get_from_drawable(drawable, cmap, 0, 0, 3, 6, w, h)
icon = gtk.status_icon_new_from_pixbuf(drawn_icon)

And an image that is only 16x11 with the transparent edges removed, what I end up with is this:

http://i237.photobucket.com/albums/ff311/Raugturi/16x11_image_positioned_in_middle.png

So how do I end up with a transparent block like the 1st one that doesn't pull in stuff from other icons?

As for the second problem, I need the ability to write on the image before converting it to the icon. I tried using draw_glyphs and it told me I should be using Pango layout/context instead. Unfortunately all the Pango tutorials I could find deal with actual windows, not the status icon. Is there a good tutorial out there for Pango that would apply to this issue (and also maybe have at least some explanation of how to tell it what font to use as all of them that I found seem to lack this and it won't write anything without it).

Note: Sorry for the lack of actual images and only one working link, apparently this is a spam prevention feature due to my lack of reputation.


Asked by: Miranda171 | Posted: 30-11-2021






Answer 1

I wrote this tool (in C, but it is designed to be a separate process) to work with any language (perl, python, tcl, lua, c, c++, bash, ksh,...) Just start it up with any number of icons with tooltips and right and left click commands (only limited by the size of the tray). Then just change your icon as needed. The easiest way to handle the icons is via SVG, since it is really easy to include other images (including png) and quickly define text or even complex (or simple) shapes using pre-formatted commands.

#include <sys/inotify.h>
#include <gtk/gtk.h>
#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define EVENT_BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )

void leftclick(GtkStatusIcon *si, gpointer s) {
    popen(s,"r"); /* exec s */
}

void rightclick(GtkStatusIcon *si, guint b,guint a_t, gpointer s) {
    popen(s,"r");
}

void refresh(gpointer si, gint fd, GdkInputCondition c) {
    char buffer[EVENT_BUF_LEN];
    read( fd, buffer, EVENT_BUF_LEN ); /* we are just clearing it & do not care what event type */
    gtk_status_icon_set_from_file(si,gtk_status_icon_get_title(si)); /* redraws */
}

int main(int argc, char *argv[]) {
    GtkStatusIcon *si; int i=1, watch, fd;
    gtk_init (&argc, &argv); /* loop through icon, tooltip, click messages */
    while (i<argc) {    fd = inotify_init(); /* get file descriptor to write on if image changes */
        si = gtk_status_icon_new_from_file(argv[i]); /* get a status icon widget */
        gtk_status_icon_set_title(si,argv[i]); /* hack to store the image path */
        watch = inotify_add_watch( fd, argv[i++], IN_CREATE | IN_MODIFY | IN_MOVED_FROM );
        gdk_input_add( fd, GDK_INPUT_READ, refresh, si ); /* inotify fd is ready for reading, refresh */
        gtk_status_icon_set_tooltip_text(si,argv[i++]);
        g_signal_connect(G_OBJECT(si), "activate", G_CALLBACK(leftclick), (gpointer) argv[i++]);
        g_signal_connect(G_OBJECT(si), "popup-menu", G_CALLBACK(rightclick), (gpointer) argv[i++]);
    }
    gtk_main();
}

Answered by: Catherine796 | Posted: 01-01-2022



Answer 2

Is there a reason you can't just use gtk.StatusIcon.set_from_file? It works fine with transparent images.

As for your second question, I highly doubt that it is possible to use pango on a gtk.StatusIcon.
Why do you need to write text on the icon?

Answered by: Oliver981 | Posted: 01-01-2022



Similar questions

python - PyQt Transparent Image Widget Background

I want to make the background of the Widget with a transparent image, not fully transparent but the corners are round and the rest of the rounded should be transparent. I can make the Widget-Background fully transparent with: self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True) but if i make my Image as the background it isnt shown..so the whole background is removed... How ...


python - Can Mayavi render a figure scene with a transparent background?

I am generating a mesh plot using mayavi.mlab and want the background opacity to be 0. (or transparent). Is this possible?


python - Wand turns transparent background to black

I am trying to grayscale with python using Wand, but when I do from wand.image import Image with Image(filename='image.png') as img: img.type = 'grayscale' img.save(filename='image_gray.png') it turns the transparent background into black. If I use one with white background it works. What do I do wrong. And also as grayscaling is Y = 0.2126 * RED + 0.7152 * GREEN + 0.0...


python - How can I make the background of an image appear transparent without PIL?

I'm trying to make a GUI in tkinter that uses one image as an overlay on top of another, but when I place the image over the lower one, the transparent area of the image appears as grey. I've searched for solutions to this, but all the results that I've found have pointed towards using PIL. Is it possible for me to use transparent, or partially transparent images in the python tkinter module without...


python - Make an image background transparent

I have an image with an orange and a white background. I want to make the white background transparent. The code below uses grabcut to make a mask. I then split the image into rgb channels and apply the mask on the alpha channel. You'll see from images below that post-grabcut and mask images are OK. I haven't been able to figure out how to apply the mask to the alpha channel. Suggestions appreciated. im...


python - How can I set the background of a transparent image to white, using PIL?

I have a PNG image with transparent background and I want to resize it to another image, but with a white background instead of a transparent one. How can I do that with PIL? Here is my code: basewidth = 200 img = Image.open("old.png") wpercent = (basewidth/float(img.size[0])) hsize = int((float(img.size[1]) * float(wpercent))) img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)hsize = int((f...


python - How to make icon background transparent in PyQt>?

I use a menu icon with white background. When I start my program I see this white background on gray menu item. It does not look nice. How to make white background transparent for not to see white color?


python - How to paste transparent image into white background?

I have a code that looks like this: from PIL import Image image = Image.open ("image.png") image.putalpha (128) background = Image.new ("RGBA", (1024, 720), "white") background = Image.alpha_composite (background, image) background.save ("newImage.png") The problem is that the background starts changing tone, as the alpha I set to the image increases, the background black, and as it d...


python - Change pixels transparent background

I have several different images in which I want to change every transparent pixel of the image into a different color. I've found a way to extract all the RGB values of the transparent pixels of an image as such: data[data[:,:,3]==0,:3][0] Now when I try to assign a different array to this pixel it doesn't work: data[data[:,:,3]==0,:3][0] = np.array([255,0,255]) p...


python - How to remove white background of image and make it transparent?

I am trying to remove the white background of few images programmatically and make it transparent. The format of the image is simple, it has a white background and a single object mainly positioned in the middle. I want to replicate the functionality of the https://remove.bg website which makes the background of the image transparent. I have tried u...


python - How can i remove a transparent background from a .png image

I try to remove the transparent background of a .png image and then scaling it to the seeable content of the image.


python - Omsnx plot has transparent background

There is a new version of osmnx and when I try to plot my graph with my color bar the image I get has a transparent background. In earlier versions this did not happen. Can anyone explain me why this transparent background appears? Here is the code: city = 'Portugal, Lisbon' G = ox.graph_from_place(city, network_type='drive', simplify=True) G_nx = nx.relabel.convert_node_labels_to_int...


python - Load Image with transparent Background

What I have tried I try to load this image with opencv in python and as you can see the image will be loaded here as png without alpha channel. But the original image has just everything transparent and only the circles are visible. In this following...


GTK Python Transparent Background for PNG Image

I am using Python and GTK 3 to overlay images onto a GStreamer video stream, and I am attempting to use the Gtk.Overlay() widget to do this. The image is a .png file with a transparent background. I am able to overlay the image just fine, but when I overlay the image it has a white square as a background rather than showing the videostream underneath. Code Snippet: overlay = Gtk.Overlay() # th...


python - How do I make my sprite image background appear transparent?

I am trying to make sprites appear as images in my pygame code. Here is one of the sprites: class Enemy(pygame.sprite.Sprite): def __init__(self): super(Enemy, self).__init__() self.surf = pygame.Surface((20, 10)) self.surf = pygame.image.load(&quot;Rocket 1.png&quot;).convert() self.rect = self.surf.get_rect( center=( random.randint(SCREEN_WIDT...


python - How to find a image with transparent background on the screen?

So, I have an image with a transparent background and dimensions (Width_1, High_1), and what I'm trying to do is to find this image (but not necessary with the same dimension) on the screen let's say with dimensions (Width_2, High_2), so with that in mind I wrote this following code: def resize_untill_find(image,bigger_or_smaller, min_size = 50 , max_size =...


python - Saving transparent PNG as JPEG on white background

Say I have an BGRA image as numpy array that looks pretty much like this: [[[233 228 230 128] [233 228 230 128] [233 228 230 0] ... [164 160 159 65] [199 197 196 65] [255 255 254 120]] That looks pretty straightforward - three colour channels + one alpha that controls transparency of pixels. Saving that numpy array in a PNG format results in an image that...


Python PIL reduce alpha level, but do not change transparent background

I want to make the visible part of image more transparent, but also do not change the alpha-level of fully-transparent background. Here's the image: and I do it like this: from PIL import Image img = I...


python - png images with transparent background don't work in pygame 2.0.0

This question already has answers here:


python - Transparent image covers frame with main window background color

I am trying to design a chess board GUI with PyQt. The board is comprised of frames. When I place a transparent PNG of a chess piece, the PNG is colored with the background of the window, thus covering the frame underneath. When there is no background color set to the window, the piece, and the square beneath it display properly. How could I set the image to not cover the frame square underneath it with the window backgrou...


python - How to make a surface with a transparent background in pygame

Can someone give me some example code that creates a surface with a transparent background in pygame?


django - python PIL - background displayed opaque instead of transparent

I want to generate 32x32 sized thumbnails from uploaded images (actually avatars). To prevent a thumbnail from being smaller than that size, I want to create a transparent 32x32 background and paste the thumbnail on it. The code below tries to do so. However, the avatar is displayed on a black and opaque background; I lose transparency information somewhere through the process. Where am I doing wrong?...


python - How to get transparent background in window with PyGTK and PyCairo?

I've been trying really hard to create a window with no decoration and a transparent background using PyGTK. I would then draw the content of the window with Cairo. But I can't get it to work. I've tried a lot of different ways, they all failed, this is one of them #!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk, sys, cairo win = None def expose (widget, event): cr = widget...


White background to transparent background using PIL python

How can i transform all white background and white elements of a png or jpg image in a transparent backgroun using PIL?


java - Detect if .swf has transparent background

Is there a way to do this programmatically in PHP, Python or Java? Use case: User uploads .swf through an upload form. Detect if it has a transparent background. If it does, change it to something else, e.g. white.


user interface - I want to make a transparent BACKGROUND frame with my python app (WxPython)

I've always wanted to make a app that's transparent, I love how it looks. I tried to make on of my apps transparent with the SetTransparent(alpha), but I bumped into a big problem. Yes it makes my app transparent (^。^), but it makes EVERYTHING transparent (=。=). I have no idea how to fix this problem. Hours of research didn't really help out. What I meant by background is, nothing el...


python - Transparent background file download from S3

I am trying to permit a python app to access various locations in a many-GB file stored in S3. I'd like to create a drop-in replacement file-like object that intelligently downloads chunks of data from S3 in a separate thread to meet seek() and read() requests. Is there a simple data structure I can use to store arbitrary intervals of the file? It must support O(log n) look-up and O(n) insertion (n=number o...


c++ - How to make wxPython, DC background transparent?

How can i make the default white DC background become invisible (transparent)? Run the following example, it shows a white background over a button. I would like to remove the white background of the DC. (to show only the red X) import wx class drawover(wx.Window): def __init__(self, parent): wx.Window.__init__(self, parent) self.Bind(wx.EVT_PAINT, self.OnPaint) self....


python - Merging background with transparent image in PIL

I have a png image as background and I want to add a transparent mesh to this background but this doesn't work as expected. The background image is converted to transparent on places where I apply transparent mesh. I am doing: from PIL import Image, ImageDraw map_background = Image.open(MAP_BACKGROUND_FILE).convert('RGBA') map_mesh = Image.new('RGBA', (width, height), (0, 0, 0, 0)) draw = ImageDraw...


python - Transparent background in gnuplot multiplot

I'd like to get a transparent background in my gnuplot figure. What I coded till now is: #! /usr/bin/python from numpy import * import Gnuplot as gp import Gnuplot.funcutils x = (1,2,3) y=(2,4,5) x1 = (3,6,8) g = gp.Gnuplot() g("set terminal svg size 200,400") g("set output 'filename.svg'") g("unset xtics") g("unset ytics") g("set multiplot layout 3,1 title 'Title here'") g("set object 1 rectangle from ...


python - How to make a surface with a transparent background in pygame

Can someone give me some example code that creates a surface with a transparent background in pygame?


python - How to use PIL to make all white pixels transparent?

I'm trying to make all white pixels transparent using the Python Image Library. (I'm a C hacker trying to learn python so be gentle) I've got the conversion working (at least the pixel values look correct) but I can't figure out how to convert the list into a buffer to re-create the image. Here's the code img = Image.open('img.png') imga = img.convert("RGBA") datas = imga.getdata() newData = list() for i...


pygame - Updating part of a surface in python, or transparent surfaces

I have an application written in python that's basically an etch-a-sketch, you move pixels around with WASD and arrow keys and it leaves a trail. However, I want to add a counter for the amount of pixels on the screen. How do I have the counter update without updating the entire surface and pwning the pixel drawings? Alternatively, can I make a surface that's completely transparent except for the text so you can se...


django - python PIL - background displayed opaque instead of transparent

I want to generate 32x32 sized thumbnails from uploaded images (actually avatars). To prevent a thumbnail from being smaller than that size, I want to create a transparent 32x32 background and paste the thumbnail on it. The code below tries to do so. However, the avatar is displayed on a black and opaque background; I lose transparency information somewhere through the process. Where am I doing wrong?...


python - Transparent FrameBuffer background in OpenGL

I want to use glClear and glClearColor to fill a frame buffer with a colour including alpha transparency. However the framebuffer always renders as opaque when binded to a texture which is rendered to the screen. I want everything which is rendered to the framebuffer to kept their transparency. I just want to change the background. See the following code: def create_texture(surface): surface...


python - How to make cStringIO transparent to another function that expects a real local file

I came up with the following problem: CODE A works right now.. I am saving a png file called chart.png locally, and then I am loading it into the proprietary function (which I do not have access). However, in CODE B, am trying to use cStringIO.StringIO() so that I do not have to write the file "chart.png" to the disk. But I cannot find a way to pass it to the pproprietaryfunction because it is expecting a real fil...


python - PIL: How to make area transparent in PNG?

I've been using PIL to crop Images, now I also want to make certain rectangular areas transparent, say from PIL import Image im = Image.open(&quot;sample.png&quot;) transparent_area = (50,80,100,200) ...


python - Matplotlib transparent line plots

I am plotting two similar trajectories in matplotlib and I'd like to plot each of the lines with partial transparency so that the red (plotted second) doesn't obscure the blue. EDIT: Here's the image with transparent lines.


python - Transparent 3D bar graphs

I would like to generate 3D bar graphs with transparent surfaces so that I can see what is going on behind tall bars. The mplot3d API docs say that keywords are allowed for the bar3d function. I pass all the required parameters but can only output graphs with solid surfaces.


python - Partially transparent scatter plot, but with a solid color bar

In Python, with Matplotlib, how to simply do a scatter plot with transparency (alpha &lt; 1), but with a color bar that represents their color value, but has alpha = 1? Here is what one gets, with from pylab import *; scatter(range(10), arange(0, 100, 10), c=range(10), alpha=0.2); color_bar = colorbar(): How can the color ba...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top