代码之家  ›  专栏  ›  技术社区  ›  uzdisral

Python使用gi将两个函数组合在一起。存储库

  •  1
  • uzdisral  · 技术社区  · 7 年前

    我正在使用 gi.repository 对于我的代码中的桌面通知,我创建了两个不同的函数,以便从本地计算机加载两个不同的图像,并根据满足的条件将它们显示在桌面通知气泡中。为此,我编写了一个简单的代码,向您展示我需要实现的目标。我很想保持我的代码尽可能干净,我想知道这两个函数是否可以合并在一起并仍然加载图像。稍后我可能会在代码中使用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 回复  |  直到 7 年前
        1
  •  2
  •   Carcigenicate    7 年前

    由于这两个函数之间唯一不同的是图像路径,只需传入:

    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 只是一个占位符。