0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】Tkinterでイベントの伝播を停止する方法(return 'break' の使い方)

Last updated at Posted at 2025-05-01

1. 概要

Tkinterでイベントバインド bind を使う場合、デフォルトの処理が意図しない動作になることがある。それを防ぎたい(イベントの伝播を停止したい)場合に、return 'break' を使用する。

2. 実装

イベントの伝播を停止しない例

下記を実行し、entry1 のEntry内で Tab キーを押下する。
すると、entry1 には何も文字は挿入されず、フォーカスが entry2 へ移る。

main.py
import tkinter as tk
from tkinter import ttk


if __name__ == '__main__':
    root = tk.Tk()

    entry1 = ttk.Entry(root)
    entry1.pack()

    entry2 = ttk.Entry(root)
    entry2.pack()

    root.mainloop()

イベントの伝播を停止する例

先の挙動を踏まえ、次のような機能を実装する。

  • entry1Tab キーを押下すると、entry1 にタブ \t が挿入される。ただし、次のウィジェット(entry2)へフォーカスはしない。
main.py
import tkinter as tk
from tkinter import ttk


def on_tab_in_entry1(event):
    entry1.insert(tk.END, '\t')
    return 'break'


if __name__ == '__main__':
    root = tk.Tk()

    entry1 = ttk.Entry(root)
    entry1.pack()

    entry2 = ttk.Entry(root)
    entry2.pack()

    entry1.bind('<Tab>', on_tab_in_entry1)

    root.mainloop()

3. return 'break' について

用語説明(事前知識)

Tcl(ティクル): スクリプト言語。
Tk: Tcl用に開発されたGUIツールキット。Tool kit 略して Tk
Tkinter: Pythonの標準ライブラリ。Pythonで Tk を使うためのラッパー。内部的には Tcl/Tk を呼び出しているが、Pythonの文法で記述できる。

機能説明

Tkinterの return 'break' は、Tcl/Tkにおける break コマンドのラッパー的な動作をしている。つまり、コールバック関数の戻り値として 'break' のような文字列を返すことで、Tcl/Tk 側で対応するコマンド(ここでは break)が実行される。

この仕様は、Tkinterの公式ドキュメントには記載されていない。

Tcl/Tk の公式ドキュメントには break コマンドの説明がある。

MULTIPLE MATCHES - Tcl8.6.16/Tk8.6.16 Documentation:

If the break command is invoked within a binding script, then that script terminates and no other scripts will be invoked for the event.

Google Translate 和訳:

バインディング スクリプト内で break コマンドが呼び出されると、そのスクリプトは終了し、イベントに対して他のスクリプトは呼び出されません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?