文本覆盖托盘图标

时间:2011-01-16 22:40:16

标签: python gtk pygtk

我有一个使用PyGTK gtk.StatusIcon的简单托盘图标:

import pygtk
pygtk.require('2.0')
import gtk


statusIcon = gtk.StatusIcon()
statusIcon.set_from_stock(gtk.STOCK_EDIT)
statusIcon.set_tooltip('Hello World')
statusIcon.set_visible(True)

gtk.main()

如何在工具提示中添加文字标签(一个或两个字符;基本上是未读计数),而不为set_from_file创建单独的图像?

3 个答案:

答案 0 :(得分:0)

import gtk
from gtk import gdk

traySize = 24

statusIcon = gtk.StatusIcon()
trayPixbuf = gdk.Pixbuf(gdk.COLORSPACE_RGB, True, 8, traySize, traySize)

## Every time you want to change the image/text of status icon:
pixbuf = gtk.image_new_from_stock(gtk.STOCK_EDIT, traySize).get_pixbuf()
pixmap = pixbuf.render_pixmap_and_mask(alpha_threshold=127)[0] ## pixmap is also a drawable
textLay = statusIcon.create_pango_layout('Hi')

## Calculate text position (or set it manually)
(text_w, text_h) = textLay.get_pixel_size()
x = (traySize-text_w) / 2
y = traySize/4 + int((0.9*traySize - text_h)/2)

## Finally draw the text and apply in status icon
pixmap.draw_layout(pixmap.new_gc(), x, y, textLay, gdk.Color(255, 0, 0))## , foreground, background)
trayPixbuf.get_from_drawable(pixmap, self.get_screen().get_system_colormap(), 0, 0, 0, 0, traySize, traySize)
statusIcon.set_from_pixbuf(trayPixbuf)

答案 1 :(得分:0)

Pango希望Widget类可以绘制,但StatusIcon不是。

import gtk
from gtk import gdk
import cairo

traySize = 24

statusIcon = gtk.StatusIcon()
trayPixbuf = gdk.Pixbuf(gdk.COLORSPACE_RGB, True, 8, traySize, traySize)

pixmap = trayPixbuf.render_pixmap_and_mask(alpha_threshold=127)[0] ## pixmap is also a drawable
cr = pixmap.cairo_create() # https://developer.gnome.org/gdk/unstable/gdk-Cairo-Interaction.html#gdk-cairo-create

# drawing
cr.select_font_face("Georgia", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
cr.set_source_rgba(0, 0, 0, 0)
cr.set_source_rgba(1, 0.1, 0.5, 1)
cr.set_font_size(30)
cr.move_to(0, 16)
cr.show_text("a")

# surf.write_to_png('test.png')

trayPixbuf.get_from_drawable(pixmap, pixmap.get_colormap(), 0, 0, 0, 0, traySize, traySize) # not sure 2nd arg is ok
trayPixbuf = trayPixbuf.add_alpha(True, 0x00, 0x00, 0x00)
statusIcon.set_from_pixbuf(trayPixbuf)

statusIcon.set_visible(True)

gtk.main()

答案 2 :(得分:0)

在GTK3中使用Gtk.OffscreenWindow的一个稍微简单的例子:

from gi.repository import Gtk

statusIcon = Gtk.StatusIcon()
window = Gtk.OffscreenWindow()
window.add(Gtk.Label("text"))
def draw_complete_event(window, event, statusIcon=statusIcon):
  statusIcon.set_from_pixbuf(window.get_pixbuf())
window.connect("damage-event", draw_complete_event)
window.show_all()

Gtk.main()

(另见stackoverflow.com/a/26208202/1476175