PySimpleGUI の Cookbook はとても勉強になるし、読んでいて楽しい。例えば、 "Recipe - Callback Function Simulation" の部分を読んでいて、なるほどなぁ、と思ったことがあった。
ある入力が受けて、その入力に応じた関数を呼ぶ、ということはよくある。イメージで言うと、変数event の値が "1" なら function1を、"2" なら function2を呼ぶ、と言うケース:
# 関数の定義
def function1():
print("function1 is called")
def function2():
print("function2 is called")
# なんらかの入力がある
event = "1"
# 場合分けで実行
if event == "1":
function1()
elif event == "2":
function2()
# event が "1" なので function1() が呼ばれる
# "function1 is called"
if とか elif とかで書いても問題なく動いてくれるのだけれども、もっとシンプルに書く方法が今回のお話。場合分けが多くなったりした時にもとても役に立つ。どうやるかというと、辞書(dictionary)を使う。入力と関数を辞書に入れておく:
# 関数の定義 (上と同じ)
def function1():
print("function1 is called")
def function2():
print("function2 is called")
# この辞書を作っておく
dispatch_dictionary = {"1":function1, "2":function2}
# なんらかの入力がある
event = "1"
# 場合分けで実行
if event in dispatch_dictionary:
function_to_call = dispatch_dictionary[event]
function_to_call()
# event が "1" なので function1() が呼ばれる
# "function1 is called"
function_to_call に function1 を一度入れておいて、それから () をつけてあげるとその関数を呼ぶことができる。
PySimpleGUIにはランチャーアプリを作って利用しているのだけれども、このやり方でコードがずいぶんスッキリしてくれた。

0 件のコメント:
コメントを投稿