2017-12-19 2 views
1

私のコードでデスクトップ通知にgi.repositoryを使用しています。ローカルマシンから2つの異なるイメージを読み込んでデスクトップ通知のバブルどんな条件が満たされているか。この目的のために私は達成する必要があることを示す簡単なコードを書いた。私はコードを可能な限りクリーンな状態に保ちたいと思っていました。これらの2つの機能を一緒にマージしてイメージを読み込むことができるのだろうかと思っていました。私は後で私のコードで8つの異なる画像を使用している可能性があり、8つの同じ機能を持っているのはうまく見えません。Pythonはgi.repositoryを使用して2つの関数を結合します

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

答えて

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は単なるプレースホルダです。

+0

私はそれだと思います!あなたは私の一日を作った。私はそれについても考えていない。ありがとうございました – uzdisral

+1

@uzdisral問題ありません。重複したコードを見つけたらすぐに、何が違うのかを見て、関数の新しいパラメータにしてみてください。適切な状況でこれを行うことができれば、コードを実際にクリーンアップする方法を学びます。 – Carcigenicate

+0

有効なポイントが取られました。それを待つことはできません – uzdisral

関連する問題