托盘图标的文本覆盖

2 投票
3 回答
2115 浏览
提问于 2025-04-16 10:04

我有一个简单的托盘图标,使用的是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

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()
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

这是一个使用 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)

撰写回答