tkinterにおいてwidgetのbind()
の戻り値をunbind()
に渡すことで解除できると思うのですが、以下のように1つ目のbind()
時のid
を渡しているのに2つ目のbind()
が解除できてしまうのはどうしてですか?
python3
1from tkinter import * 2 3root = Tk() 4button = Button(root, text='Push Me', font=('', 40)) 5button.pack() 6 7bind_id = button.bind('<Button-1>', lambda event: print('1st callback')) 8button.unbind('<Button-1>', bind_id) 9bind_id2 = button.bind('<Button-1>', lambda event: print('2nd callback')) 10button.unbind('<Button-1>', bind_id) # 一つ目のbind()時のidを渡している 11 12root.mainloop()
出てきたButtonを押しても何も出力されないので二つ目のbind()
も解除されているように思えます。
環境
- OS ... LinuxMint18.2 MATE Edition (Ubuntu16.04LTS派生)
- Python 3.6.2
- tkinter.TkVersion ... 8.6
- tkinter.TclVersion ... 8.6
追記
上のコードでは指摘された通りbind_id
とbind_id2
が同じになっていました。なのでErrorが怒らなかったものと思われます。ただそれでもはやりunbind()
が正しく機能していないように思えます。理由は以下のコードで
python
1from tkinter import * 2 3 4root = Tk() 5button = Button(root, text='Push Me', font=('', 40)) 6button.pack() 7 8bind_id = button.bind('<Button-1>', lambda event: print('1st callback'), '+') 9print(bind_id) 10bind_id2 = button.bind('<Button-1>', lambda event: print('2nd callback'), '+') 11print(bind_id2) 12 13button.unbind('<Button-1>', bind_id) # A 14# button.unbind('<Button-1>', bind_id2) # B 15 16root.mainloop()
A行とB行のどちらか一つを有効にしただけで、callback関数は両方共呼ばれなくなってしまうからです。
追記2
上の問題に関してはstackoverflowにあったこの投稿を参考にunbind()
を修正した所、期待通りの動作をしてくれました。
python
1from tkinter import * 2 3 4def new_unbind(self, sequence, funcid=None): 5 """Unbind for this widget for event SEQUENCE the 6 function identified with FUNCID.""" 7 if not funcid: 8 self.tk.call('bind', self._w, sequence, '') 9 return 10 func_callbacks = self.tk.call('bind', self._w, sequence, None).split('\n') 11 new_callbacks = [l for l in func_callbacks if l[6:6 + len(funcid)] != funcid] 12 self.tk.call('bind', self._w, sequence, '\n'.join(new_callbacks)) 13 self.deletecommand(funcid) 14 15 16old_unbind = Misc.unbind 17Misc.unbind = new_unbind 18 19 20root = Tk() 21button = Button(root, text='Push Me', font=('', 40)) 22button.pack() 23 24bind_id = button.bind('<Button-1>', lambda event: print('1st callback'), '+') 25print(bind_id) 26bind_id2 = button.bind('<Button-1>', lambda event: print('2nd callback'), '+') 27print(bind_id2) 28 29# button.unbind('<Button-1>', bind_id) # A 30button.unbind('<Button-1>', bind_id2) # B 31 32root.mainloop()
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/11/10 14:14
2018/11/10 14:44
2018/11/10 15:39 編集
2018/11/10 15:39
2018/11/11 00:54
2018/11/11 03:09
2018/11/11 05:47