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?

Tkinterで謎に詰まってしまう「遅延評価」の対処法

Posted at

環境

Python 3.13
Tkinterインストール済み

「遅延評価」によっておきるバグ

Tkinterでフレーム等を使いリストを表示し、その中のボタンにfor文でコマンドを設定したら、for文のカウントと一致せずにコマンドが設定されてしまうことがあります(下は例のコードです)

import tkinter as tk
root = tk.Tk()
root.geometry("500x300")
button = []
for i in range(5):
    button.append(
        tk.Button(
            root,
            text=str(i),
            command=lambda:print(i)
        )
    )
    button[-1].pack(fill="x")
root.mainloop()

# 0,1,2,3,4いずれのボタンを押しても4がprintされてしまう

解決方法

commandの引数を変えましょう

import tkinter as tk
root = tk.Tk()
root.geometry("500x300")
button = []
for i in range(5):
    button.append(
        tk.Button(
            root,
            text=str(i),
-            command=lambda:print(i)
+            command=lambda count=i:print(count)
        )
    )
    button[-1].pack(fill="x")
root.mainloop()

# きちんと押したボタンの数字がprintされる
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?