Python使用gi.repository结合了两个函数

时间:2017-12-19 02:09:19

标签: python-2.7 notifications

我在代码中使用gi.repository进行桌面通知,我创建了2个不同的函数,以便从本地计算机加载2个不同的图像,并将它们显示在桌面通知气泡中,具体取决于条件是什么满足。为此我编写了一个简单的代码来向您展示我需要实现的目标。我希望尽可能保持我的代码尽可能干净,并且想知道这两个函数是否可以合并在一起并仍然加载图像。我可能会在我的代码中使用8个不同的图像,并且有8个相同的功能看起来不太好。

import gi
gi.require_version("Notify", "0.7")
from gi.repository import Notify, GdkPixbuf

def sunny(arg1, arg2):
    notification = Notify.Notification.new(arg1, arg2)
    image = GdkPixbuf.Pixbuf.new_from_file("_sunny_day.png")
    notification.set_icon_from_pixbuf(image)
    notification.set_image_from_pixbuf(image)
    notification.show()

def cloudy(arg1, arg2):
    notification = Notify.Notification.new(arg1, arg2)
    image = GdkPixbuf.Pixbuf.new_from_file("_cloudy_day.png")
    notification.set_icon_from_pixbuf(image)
    notification.set_image_from_pixbuf(image)
    notification.show()

while 1:
    var1 = 'Something will be here, maybe URL'

    if var1 == 'Sunny':
        sunny('Arg1', 'Arg2')
    elif var1 == 'Cloudy':
        cloudy('Arg1', 'Arg2')

An Example

1 个答案:

答案 0 :(得分:2)

由于两个函数之间唯一不同的是图像路径,只需将其传递给:

def weather(arg1, arg2, image_path):
    notification = Notify.Notification.new(arg1, arg2)
    image = GdkPixbuf.Pixbuf.new_from_file(image_path) # Here
    notification.set_icon_from_pixbuf(image)
    notification.set_image_from_pixbuf(image)
    notification.show()

然后使用它:

weather(arg1, arg2, "_sunny_day.png")
weather(arg1, arg2, "_cloudy_day.png")

我并不确切地知道您想要将此功能称为什么。 weather只是一个占位符。

相关问题