Hello,

Il y a un aspect des expressions lambda qui m'échappe, je ne sais pas si le problème est entre la chaise et le clavier(c'est le plus vraisemblable), dans tkinter ou dans python... Quoiqu'il en soit, en cliquant les boutons les uns après les autres, je m'attendais au résultat 1 mais j'obtiens le résultat 2... S'il n'est pas possible de créer des lambda dans une boucle, j'aimerais savoir pourquoi.

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 
import Tkinter as tk
 
def hook1(*args):
    print "hook1", args
 
def hook2(*args):
    print "hook2", args
 
def hook3(*args):
    print "hook3", args
 
def hook4(*args):
    print "hook4", args
 
def hook5(*args):
    print "hook5", args
 
def hook6(*args):
    print "hook6", args
 
def hook7(*args):
    print "hook7", args
 
def hook8(*args):
    print "hook8", args
 
def hook9(*args):
    print "hook9", args
 
def hook10(*args):
    print "hook10", args
 
hooks = (hook1, hook2, hook3, hook4, hook5, hook6, hook7, hook8, hook9, hook10)
 
win = tk.Tk()
 
tk.Button(win, text="BATCH 1", width=16, command=lambda param=1:hooks[0](param)).grid()
tk.Button(win, text="BATCH 2", width=16, command=lambda param=2:hooks[1](param)).grid()
tk.Button(win, text="BATCH 3", width=16, command=lambda param=3:hooks[2](param)).grid()
tk.Button(win, text="BATCH 4", width=16, command=lambda param=4:hooks[3](param)).grid()
tk.Button(win, text="BATCH 5", width=16, command=lambda param=5:hooks[4](param)).grid()
 
for x in range(5,10):
    tk.Button(win, text="BATCH %u"%(x+1), width=16, command=lambda param=x+1:hooks[x](param)).grid()
win.mainloop()
Résultat 1
hook1 (1,)
hook2 (2,)
hook3 (3,)
hook4 (4,)
hook5 (5,)
hook6 (6,)
hook7 (7,)
hook8 (8,)
hook9 (9,)
hook10 (10,)

Résultat 1
hook1 (1,)
hook2 (2,)
hook3 (3,)
hook4 (4,)
hook5 (5,)
hook10 (6,)
hook10 (7,)
hook10 (8,)
hook10 (9,)
hook10 (10,)